<?php
/**
 *@author sparkguo 
 *@date 2017-09-22  订单报表程序
 */
defined('BASEPATH') OR exit('No direct script access allowed');
class Report extends CI_Controller {

	function __construct(){
		parent::__construct();
		$this->load->model('Function_m','fun');
		$this->load->model('Report_m','m');
		$this->load->model('Datareport_m','d');
		$this->pageSize =$this->config->item('pagenum');
	 }

	function ajaxbutton(){
		$op = trim($this->input->get_post('op'));	
		/******日收入报表*******
		***	查询订单db_order_list 中dates日期订单
		***	排除作废的订单
		*** 通过订单和订单SELL得到交易金额，实收运费。小计，商品成本，商品销量，订单量
		*****/
		if($op == 'immediatereportDay'){
            $this->incomeForDay();
		}
		/******日销售报表*******
		***	查询订单db_order_list 中dates日期订单
		***	排除作废的订单
		*** 通过订单和订单SELL得到交易金额，实收运费。小计，商品成本，商品销量，订单量
		*****/
		if($op =='reportDay'){
            $this->salesByDay();
		}
        //月销售报表
		if($op =='salesByMonth'){
            $this->salesByMonth();
		}
        //热销商品排名
        if($op =='salesGoodsRank'){
            $this->salesGoodsRank();
		}
        //热销店铺排名
        if($op =='salesShopRank'){
            $this->salesShopRank();
		}
        //地区销售额报表
        if($op =='salesByArea'){
            $this->salesByArea();
		}
        //国家销售额报表
        if($op =='salesByCountry'){
            $this->salesByCountry();
		}
        //返回店铺列表
        if($op =='getShopList'){
            $this->getShopList();
		}
        if($op=='reportStore'){
            $this->reportStore();    
        }
        if($op=='diffOrders'){
            $this->diffOrders();
        }
        if($op=='getShopSaleNum'){
            $this->getShopSaleNum();
        }
        if($op=='goodsPublishAnalysis'){
            $this->goodsPublishAnalysis();
        }
	}
    
    public function incomeForDay(){

    	$starttime =$getstarttime= $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')+86400):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
       
        
    	//查询开始与结束时间每天的日收入
    	$shopname	   = $this->input->get('shopname');
        $shopname=trim($shopname,',');
        $can_visit_shop=$this->getViewShops();
        if($can_visit_shop!='isadmin' && $shopname==''){
            if(!empty($getstarttime)){
                $shopname=$can_visit_shop;
            }
        }
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'shopname'=>$shopname);
    	if (count($shopname) >0) {
    	    $shopname=explode(',',$shopname);
    		$whereshop = implode("','",$shopname);
    	}
        if($whereshop)$wherestr=" AND shopname in('".$whereshop."')";
		
        if(!empty($getstarttime)){
            $orders=$this->m->getOrderAmountList($starttime,$wherestr,$endtime,"dates",'dates');
		
            $daysales=array();
            foreach($orders as $key=>$val){
                $subtotal = $val['goods_amount_total'] +$val['shipping_fee_total'];
                $subzhic = $val['costprice_total']+$freight+$val['realexpress_fre']+ $val['payfee_total']+ $val['platform_fee_total'];
                $lirun = $subtotal - $subzhic;
        		if($subtotal){
        			$maoliv = round(($lirun/$subtotal)*100,2);
        		}else{
        			$maoliv=0;
        		}    
                $res=array("orderAmount"=>$val['goods_amount_total'],"shipping_fee"=>$val['shipping_fee_total'],"subtotal"=>number_format($subtotal,2),
                "cosprice"=>$val['costprice_total'],"freight"=>$val['realexpress_fre']
                ,"platformfee"=>$val['platform_fee_total'],"payfee"=>$val['payfee_total'],'orderDate'=>$val['dates'],
                "subzhic"=>number_format($subzhic,2),"goodsnNum"=>$val['sell_total'],"orderNum"=>$val['order_num'],"lirun"=>number_format($lirun,2),"maoliv"=>$maoliv."%");
                $daysales[]=$res;
                
          		$allorderAmount = $allorderAmount+$val['goods_amount_total'];	//合计
        		$allshipping_fee = $allshipping_fee+$val['shipping_fee_total'];
        		$allsubtotal = $allsubtotal+$subtotal;
        		$allcosprice = $allcosprice+$val['costprice_total'];
        		$allnum = $allnum+$val['sell_total'];
        		$allorderNum = $allorderNum+$val['order_num'];
        		$allfreight = $allfreight+$val['realexpress_fre'];
        		$allplatformfee = $allplatformfee+$val['platform_fee_total'];
        		$allpayfee = $allpayfee+$val['payfee_total'];
        		$allsubzhic = $allsubzhic+$subzhic;
        		$alllirun = $alllirun+$lirun;
            }
            $tpl_data['list']=$daysales;
            if($allsubtotal)
            		$allmaolv = round(($alllirun / $allsubtotal)*100,2);
            
        	$this->tpl->assign("allorderAmount", number_format($allorderAmount,2));
        	$this->tpl->assign("allshipping_fee", number_format($allshipping_fee,2));
        	$this->tpl->assign("allsubtotal", number_format($allsubtotal,2));
        	$this->tpl->assign("allcosprice", number_format($allcosprice,2));
        	$this->tpl->assign("allnum", $allnum);
        	$this->tpl->assign("allorderNum", $allorderNum);
        	$this->tpl->assign("allfreight", number_format($allfreight,2));
        	$this->tpl->assign("allpayfee", number_format($allpayfee,2));
        	$this->tpl->assign("allsubzhic", number_format($allsubzhic,2));
        	$this->tpl->assign("alllirun", number_format($alllirun,2));
        	$this->tpl->assign("allmaolv", $allmaolv."%");
        	$this->tpl->assign("allplatformfee", number_format($allplatformfee,2));
        }
        $this->tpl->assign($tpl_data);
    	$this->tpl->display("report/immediatereportDay.tpl");
    }
    
    //导常数据订单
    public function diffOrders(){
        //$data_orders=$this->fun->getdatabaseslist('d_shop', " AND del_flag= 0 AND platfrom=2", 'id,name', ' order by name asc');
        $date_where= " 1=1";
        $data_orders=$this->fun->getdatabaseslist("db_order_list B left join db_order_sell A on A.order_id=B.order_id","$wherestr and  {$date_where} AND
          order_status !=6 AND order_status !=7 limit 10");
        $fba_orders='';
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'list'=>$data_orders);
        $this->tpl->assign($tpl_data);
        $this->tpl->display("report/diffOrders.tpl");    
    }
  
    
    //日收入统计
    public function incomeForDay_bak(){
        $starttime = $this->input->get_post('starttime');	//开始时间
		$endtime   = $this->input->get_post('endtime');		//结束时间
		//查询开始与结束时间每天的日收入
		$shopname	   = $this->input->get_post('shopname');
		if (count($shopname) >0) {
			$whereshop = implode("','",$shopname);
		}
		$list ="";
		$allorderAmount=$allshipping_fee=$allsubtotal=$allcosprice=$allnum=$allorderNum=0;
		$diff = strtotime($endtime) - strtotime($starttime);
		$diffDay = $diff / (24*60*60);
		for ($i = 0; $i <= $diffDay; $i++){
			$orderDate =  date('Y-m-d', (strtotime($starttime) + $i * 24 * 60 * 60 ));
			/******通过日期获取订单量*******/
			$orderNum = $this->m->getOrderNum($orderDate,$whereshop);//订单量
			/******通过日期获取订单交易金额*******/
			$orderAmount = $this->m->getOrderAmount($orderDate,$whereshop);//订单交易金额
			/******通过日期获取订单实收运费*******/
			$shipping_fee = $this->m->getOrdershippingfee($orderDate,$whereshop);//订单实收运费
			/******通过日期获取所有商品成本*******/
			$goodsprice = $this->m->getSellgoodsprice($orderDate,$whereshop);//商品成本
			//小计快递和收入金额
			$subtotal = $shipping_fee +$orderAmount;

			$list[$i]["orderDate"] = $orderDate;
			$list[$i]["cosprice"] = $goodsprice['cosprice'];
			$list[$i]["goodsnNum"] = $goodsprice['goodsnNum'];
			$list[$i]["shipping_fee"] = $shipping_fee;
			$list[$i]["orderAmount"] = $orderAmount;
			$list[$i]["subtotal"] = $subtotal;
			$list[$i]["orderNum"] = $orderNum;

			$allorderAmount = $allorderAmount+$orderAmount;	//合计
			$allshipping_fee = $allshipping_fee+$shipping_fee;
			$allsubtotal = $allsubtotal+$subtotal;
			$allcosprice = $allcosprice+$goodsprice['cosprice'];
			$allnum = $allnum+$goodsprice['goodsnNum'];
			$allorderNum = $allorderNum+$orderNum;

		}
		$this->tpl->assign("list", $list);
		$this->tpl->assign("allorderAmount", $allorderAmount);
		$this->tpl->assign("allshipping_fee", $allshipping_fee);
		$this->tpl->assign("allsubtotal", $allsubtotal);
		$this->tpl->assign("allcosprice", $allcosprice);
		$this->tpl->assign("allnum", $allnum);
		$this->tpl->assign("allorderNum", $allorderNum);
		$this->tpl->display("report/immediatereportDay.tpl");
    }
    
    //日销售统计
    public function salesByDay(){
        
    	$starttime =$getstarttime= $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')+86400):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
        
    
    	//查询开始与结束时间每天的日收入
    	$shopname	   = $this->input->get('shopname');
        $shopname=trim($shopname,',');
        $can_visit_shop=$this->getViewShops();
        if($can_visit_shop!='isadmin' && $shopname==''){
            if(!empty($getstarttime)){
                $shopname=$can_visit_shop;
            }
        }
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'shopname'=>$shopname);
    	if (count($shopname) >0) {
    	    $shopname=explode(',',$shopname);
    		$whereshop = implode("','",$shopname);
    	}
        if($whereshop)$wherestr=" AND shopname in('".$whereshop."')";
	
        if(!empty($getstarttime)){
            $orders=$this->m->getOrderAmountList($starttime,$wherestr,$endtime,"dates",'dates');
            $daysales=array();
            foreach($orders as $key=>$val){
                $subtotal = $val['goods_amount_total'] +$val['shipping_fee_total'];
                $subzhic = $val['costprice_total']+$freight+$val['realexpress_fre']+ $val['payfee_total']+ $val['platform_fee_total'];
                $lirun = $subtotal - $subzhic;
        		if($subtotal){
        			$maoliv = round(($lirun/$subtotal)*100,2);
        		}else{
        			$maoliv=0;
        		}    
                $res=array("orderAmount"=>$val['goods_amount_total'],"shipping_fee"=>$val['shipping_fee_total'],"subtotal"=>number_format($subtotal,2),
                "cosprice"=>$val['costprice_total'],"freight"=>$val['realexpress_fre']
                ,"platformfee"=>$val['platform_fee_total'],"payfee"=>$val['payfee_total'],'orderDate'=>$val['dates'],
                "subzhic"=>number_format($subzhic,2),"goodsnNum"=>$val['sell_total'],"orderNum"=>$val['order_num'],"lirun"=>number_format($lirun,2),"maoliv"=>$maoliv."%");
                $daysales[]=$res;
                
          		$allorderAmount = $allorderAmount+$val['goods_amount_total'];	//合计
        		$allshipping_fee = $allshipping_fee+$val['shipping_fee_total'];
        		$allsubtotal = $allsubtotal+$subtotal;
        		$allcosprice = $allcosprice+$val['costprice_total'];
        		$allnum = $allnum+$val['sell_total'];
        		$allorderNum = $allorderNum+$val['order_num'];
        		$allfreight = $allfreight+$val['realexpress_fre'];
        		$allplatformfee = $allplatformfee+$val['platform_fee_total'];
        		$allpayfee = $allpayfee+$val['payfee_total'];
        		$allsubzhic = $allsubzhic+$subzhic;
        		$alllirun = $alllirun+$lirun;
            }
            $tpl_data['list']=$daysales;
            //dump($daysales);
            if($allsubtotal)
            		$allmaolv = round(($alllirun / $allsubtotal)*100,2);
            
        	$this->tpl->assign("allorderAmount", number_format($allorderAmount,2));
        	$this->tpl->assign("allshipping_fee", number_format($allshipping_fee,2));
        	$this->tpl->assign("allsubtotal", number_format($allsubtotal,2));
        	$this->tpl->assign("allcosprice", number_format($allcosprice,2));
            $this->tpl->assign("imglist", array_reverse($daysales));
        	$this->tpl->assign("allnum", $allnum);
        	$this->tpl->assign("allorderNum", $allorderNum);
        	$this->tpl->assign("allfreight", number_format($allfreight,2));
        	$this->tpl->assign("allpayfee", number_format($allpayfee,2));
        	$this->tpl->assign("allsubzhic", number_format($allsubzhic,2));
        	$this->tpl->assign("alllirun", number_format($alllirun,2));
        	$this->tpl->assign("allmaolv", $allmaolv."%");
        	$this->tpl->assign("allplatformfee", number_format($allplatformfee,2));
        }
        $this->tpl->assign($tpl_data);
    	$this->tpl->display("report/reportDay.tpl");
    }
    //月销售报表
    public function salesByMonth(){

        $start_month=$getstarttime=$this->input->get("start_month");
        $end_month=$this->input->get("end_month");
        $start_month=$start_month==''?date("Y-m",strtotime('-3 month')):$start_month;
        $end_month=$end_month==''?date("Y-m"):$end_month;
        $shopname	   = $this->input->get('shopname');
        
        $shopname=trim($shopname,',');
        $can_visit_shop=$this->getViewShops();
        if($can_visit_shop!='isadmin' && $shopname==''){
            if(!empty($getstarttime)){
                $shopname=$can_visit_shop;
            }
        }
        $tpl_data=array('start_month'=>$start_month,'end_month'=>$end_month,'shopname'=>$shopname,'list'=>array());
        
    	if (count($shopname) >0) {
    	    $shopname=explode(',',$shopname);
    		$whereshop = implode("','",$shopname);
    	}
        if($whereshop)$wherestr=" AND shopname in('".$whereshop."')";
        
        $starttime = $start_month."-01";	//开始时间
        $endtime=date("Y-m-d",strtotime("+1 month -1day",strtotime("$end_month-01")));
        
        if(!empty($getstarttime)){
            $orders=$this->m->getSalesByMonth($starttime,$wherestr,$endtime,"dates",'dates');
            $daysales=array();
            foreach($orders as $key=>$val){
                $subtotal = $val['goods_amount_total'] +$val['shipping_fee_total'];
                $subzhic = $val['costprice_total']+$freight+$val['realexpress_fre']+ $val['payfee_total']+ $val['platform_fee_total'];
                $lirun = $subtotal - $subzhic;
        		if($subtotal){
        			$maoliv = round(($lirun/$subtotal)*100,2);
        		}else{
        			$maoliv=0;
        		}    
                $res=array("orderAmount"=>number_format($val['goods_amount_total'],2),"shipping_fee"=>number_format($val['shipping_fee_total'],2),"subtotal"=>number_format($subtotal,2),
                "cosprice"=>number_format($val['costprice_total'],2),"freight"=>$val['realexpress_fre'],'month'=>$val['month'],
                "platformfee"=>number_format($val['platform_fee_total'],2),"payfee"=>number_format($val['payfee_total'],2),'orderDate'=>$val['dates'],
                "subzhic"=>number_format($subzhic,2),"goodsnNum"=>$val['sell_total'],"orderNum"=>$val['order_num'],"lirun"=>number_format($lirun,2),"maoliv"=>$maoliv."%");
                $daysales[]=$res;
                
          		$allorderAmount = $allorderAmount+$val['goods_amount_total'];	//合计
        		$allshipping_fee = $allshipping_fee+$val['shipping_fee_total'];
        		$allsubtotal = $allsubtotal+$subtotal;
        		$allcosprice = $allcosprice+$val['costprice_total'];
        		$allnum = $allnum+$val['sell_total'];
        		$allorderNum = $allorderNum+$val['order_num'];
        		$allfreight = $allfreight+$val['realexpress_fre'];
        		$allplatformfee = $allplatformfee+$val['platform_fee_total'];
        		$allpayfee = $allpayfee+$val['payfee_total'];
        		$allsubzhic = $allsubzhic+$subzhic;
        		$alllirun = $alllirun+$lirun;
            }
            $tpl_data['list']=$daysales;
            if($allsubtotal)
            		$allmaolv = round(($alllirun / $allsubtotal)*100,2);
            
        	$this->tpl->assign("allorderAmount", number_format($allorderAmount,2));
        	$this->tpl->assign("allshipping_fee", number_format($allshipping_fee,2));
        	$this->tpl->assign("allsubtotal", number_format($allsubtotal,2));
        	$this->tpl->assign("allcosprice", number_format($allcosprice,2));
        	$this->tpl->assign("allnum", $allnum);
        	$this->tpl->assign("allorderNum", $allorderNum);
        	$this->tpl->assign("allfreight", number_format($allfreight,2));
        	$this->tpl->assign("allpayfee", number_format($allpayfee,2));
        	$this->tpl->assign("allsubzhic", number_format($allsubzhic,2));
        	$this->tpl->assign("alllirun", number_format($alllirun,2));
        	$this->tpl->assign("allmaolv", $allmaolv."%");
        	$this->tpl->assign("allplatformfee", number_format($allplatformfee,2));
        }
        $this->tpl->assign($tpl_data);
        $this->tpl->display("report/salesbymonth.tpl");    
    }
    
    public function salesByArea(){
    	$starttime = $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')+86400):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime);
        
    	//查询开始与结束时间每天的日收入
    	$shopname	   = $this->input->get('shopname');
    	if (count($shopname) >0) {
    		$whereshop = implode("','",$shopname);
    	}
        if($whereshop)$wherestr=" AND shopname in('".$whereshop."')";
        $orders=$this->m->getOrderAmountList($starttime,$wherestr,$endtime,"province");
        $tpl_data['list']=$orders;
        $allmaolv=0;
     
        foreach($orders as $key=>$areaorder){
        		$allmaolv+=$areaorder['goods_amount_total']+$areaorder['shipping_fee_total'];
        }
        $tpl_data['allmaolv']=$allmaolv;
        $this->tpl->assign($tpl_data);
         $this->tpl->display("report/salesByArea.tpl");    
    }
    
    public function salesByCountry(){
    	$starttime = $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')+86400):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime);
        
    	//查询开始与结束时间每天的日收入
    	$shopname	   = $this->input->get('shopname');
    	if (count($shopname) >0) {
    		$whereshop = implode("','",$shopname);
    	}
        if($whereshop)$wherestr=" AND shopname in('".$whereshop."')";
        $orders=$this->m->getOrderAmountList($starttime,$wherestr,$endtime,"country_cn");
        $tpl_data['list']=$orders;
        $allmaolv=0;
        foreach($orders as $key=>$areaorder){
      		$allmaolv+=$areaorder['goods_amount_total']+$areaorder['shipping_fee_total'];
        }
        $tpl_data['allmaolv']=$allmaolv;
        $this->tpl->assign($tpl_data);
         $this->tpl->display("report/salesByCountry.tpl");    
    }
    
    public function newProductSales(){

        $starttime = $getstarttime = $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $ordertype=$this->input->get("ordertype");
        $skunumber=$this->input->get("skunumber");
        $rownum=$this->input->get('rownum');
        $rownum=$rownum==0?50:$rownum;
        $ordertype=$ordertype==''?"sell_total":$ordertype;
        $factory_id=$this->input->get("factory_id");

		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$factory_id=1;
		}
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$factory_id=2;
		}
		if($_COOKIE["classid"] ==16)	//工厂3人员
		{
			$factory_id=7;
		}
		 $create=$this->input->get("create");
        
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
        $shopname	   = $this->input->get('shopname');
        $shopname=trim($shopname,',');
        $can_visit_shop=$this->getViewShops();
        if($can_visit_shop!='isadmin' && $shopname==''){
            if(!empty($getstarttime)){
                $shopname=$can_visit_shop;
            }
        }
       $goods_sku=$this->input->get("goods_sku");
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'shopname'=>$shopname,
            'rownum'=>$rownum,'ordertype'=>$ordertype,'skunumber'=>$skunumber,"goods_sku"=>$goods_sku,'factory_id'=>$factory_id,'create'=>$create);
            
        $retdatas=$this->m->newProductSalesList($starttime,$endtime,$wherestr,$rownum,$ordertype,$factory_id,$create); 
        $retdatas['list']=$retdatas['list']==''?array():$retdatas['list'];
            $orders=$retdatas['list'];
            $diff_days=floor((strtotime($endtime)-strtotime($starttime))/86400);
            $allmaolv=0;
            foreach($orders as $key=>$areaorder){
                $good_id_arr[]=$areaorder['goods_id'];
               $goodinfo = $this->fun->getdatabasesdetail("db_goods"," AND goods_id=".$areaorder['goods_id']);
                if($goodinfo){
                    $orders[$key]['goods_name']= $goodinfo['goods_name'];   
                }
                $areaorder['shipping_fee_total']=round($areaorder['shipping_fee_total'],2);
                $areaorder['shipping_expectfee_total']=round($areaorder['shipping_expectfee_total'],2);
                $areaorder['platform_fee_total']=round($areaorder['platform_fee_total'],2);
                $areaorder['payfee_total']=round($areaorder['payfee_total'],2);
                $areaorder["goodsinfo"] = $goodinfo;
                $orders[$key]=$areaorder;
            }

            foreach($orders as $key=>$v){
                if($diff_days>0){
                    $orders[$key]['day_sales']=round($v['sell_total']/$diff_days,2);    
                }else{
                    $orders[$key]['day_sales']=$v['sell_total'];
                }
                $orders[$key]['maoliv']=@round(($v['goods_amount_total']+$v['shipping_fee_total']-$v['costprice_total']-$v['platform_fee_total']-$v['payfee_total']-$v['realexpress_fre']-$v['shipping_expectfee_total'])/($v['goods_amount_total']+$v['shipping_fee_total']),4)*100;
                $total['goods_amount_total']+=$v['goods_amount_total'];
                $total['shipping_fee_total']+=$v['shipping_fee_total'];
                $total["costprice_total"]+=$v['costprice_total'];
                $total['shipping_expectfee_total']+=$v['shipping_expectfee_total'];
                $total['platform_fee_total']+=$v['platform_fee_total'];
                $total['payfee_total']+=$v['payfee_total'];
                $total['maoliv_avg']+=$v['maoliv_avg'];
                $total['sell_total']+=$v['sell_total'];
            }
            $total['have_total']=$total['goods_amount_total']+$total['shipping_fee_total'];
            $total['give_total']=$total['costprice_total']+$total['platform_fee_total']+$total['payfee_total']+$total['shipping_expectfee_total'];
            $total['maoli_total']=$total['have_total']-$total['give_total'];
            if($total['have_total']>0){
                $total['maoliv_avg']=round($total['maoli_total']/$total['have_total'],4)*100;    
            }
            //$total['day_sales']=$diff_days>0?round($total['sell_total']/$diff_days/$rownum,2):$total['sell_total'];
            $tpl_data['total_datas']=$retdatas['total'];
            
            $tpl_data['list']=$orders;
            $tpl_data['total']=$total;
        $this->tpl->assign($tpl_data);
		
		$userlist = $this->fun->getdatabaseslist('db_product_develop'," AND createName is NOT NULL ",'DISTINCT(createName)');
		foreach($userlist as $key=>$rs)
		{
			$yuanl[] = $rs['createName'];
		}
        $this->tpl->assign("userlist", $yuanl);

        $this->tpl->display("report/newProductSales.tpl");  
    }
    
    
    public function productDevelopAnalysis(){
   	    $starttime = $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')+86400):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
        $order_by_data=$this->input->get('orderdata');
        $order_by_data=$order_by_data==''?1:$order_by_data;
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'orderdata'=>$order_by_data);
        $wherestr=" and status=6 && overtime>0";
        $goods_sku=$this->input->get("goods_sku");
        $factory_id=$this->input->get("factory_id");
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$factory_id=1;
		}
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$factory_id=2;
		}
		if($_COOKIE["classid"] ==16)	//工厂3人员
		{
			$factory_id=7;
		}
        
        if($goods_sku!=''){
            $wherestr.=" and A.goods_sn in('$goods_sku')";
        }
        if($factory_id!=''){
            $wherestr.=" and supplier in('$factory_id')";
        }
        $six_month=date("Y-m",strtotime("-12 month"));

        
        $countlist = $this->fun->getdatabaseslist('db_product_develop',"$wherestr and DATE_FORMAT(FROM_UNIXTIME(overtime),'%Y-%m')>='$six_month'",
            "DATE_FORMAT(FROM_UNIXTIME(overtime),'%Y-%m') month,COUNT(id) as finish_goods,supplier",
            " group BY DATE_FORMAT(FROM_UNIXTIME(overtime),'%Y-%m'),supplier order by month desc");
	
        $doing_goods=$this->fun->getdatabaseslist('db_product_develop'," and instime>='$six_month'",
            "DATE_FORMAT(FROM_UNIXTIME(overtime),'%Y-%m') month,supplier,overtime,instime"," order by month desc");
        $doing_numbers=array();
        $month_develop_data=array();
        foreach($doing_goods as $key=>$info){
            $doing_goods[$key]['develop_day']=round(($info['overtime']-strtotime($info['instime']))/86400);
            $info['overdate']=date('Y-m',$info['overtime']);
            $info['insertdate']=date("Y-m",strtotime($info['instime']));
            $infomonth=0;
            while($infomonth<6){
                $one_month=date("Y-m",strtotime("-{$infomonth}month"));
                if($info['insertdate']<=$one_month && ($info['overdate']>$one_month || $info['overtime']==0)){
                    $doing_numbers[$info['supplier'].$one_month]+=1;
                }
                $infomonth+=1;
            }
            $month_develop_data[$info['supplier'].date('Y-m',$info['overtime'])][]=$doing_goods[$key]['develop_day'];               
        }
		

        $avg_made_days=array();
        foreach($month_develop_data as $key=>$vallist){
            $total=0;
            foreach($vallist as $index=>$val){
                $total+=$val;    
            }
            $avg_made_days[$key]=round($total/count($vallist));
        }
        $this->tpl->assign('doing_numbers',$doing_numbers);
        foreach($countlist as $key=>$developGood){
            $countlist[$key]['doing_numbers']=$doing_numbers[$developGood['supplier'].$developGood['month']];
            $countlist[$key]['avg_made_day']=$avg_made_days[$developGood['supplier'].$developGood['month']];

        }
        
        $tpl_data['countlist']=$countlist;
        $list = $this->fun->getdatabaseslist('db_product_develop',"$wherestr  limit 30");
        foreach($list as $key=>$developGood){
            $list[$key]['overdate']=date("Y-m-d",$developGood['overtime']);
            $list[$key]['doing_numbers']=$doing_numbers[$developGood['month'].$developGood['supplier']];
            $list[$key]['develop_day']=round(($developGood['overtime']-strtotime($developGood['instime']))/86400);
        }
        $tpl_data['goodslist']=$list;
        $this->tpl->assign($tpl_data);
        $this->tpl->display("report/productDevelopAnalysis.tpl"); 
    }
    
    public function goodsPublishAnalysis(){
		
		$times = $this->input->get_post('t');
		$times = trim($times);
		if($times)
		{
			$where=" AND  FROM_UNIXTIME(UNIX_TIMESTAMP(linkUrl_addtime),'%Y-%m')  = '".$times."'";
			$this->tpl->assign("times",$times);
		}
		

        $datelist = $this->fun->getdatabaseslist("db_product_develop"," AND linkUrl_addtime !='' $where " ," DISTINCT(FROM_UNIXTIME(UNIX_TIMESTAMP(linkUrl_addtime),'%Y-%m')) as dates ",' order by dates DESC');//日期
		
		$other = $this->input->get_post('other');
		$other = trim($other);
		if($other)
		{
			$this->tpl->assign("other",$other);
			$external = array($other);
		}else{
			$externalbuyreceivers = $this->config->item('externalbuyreceivers');
			$external = explode("|",$externalbuyreceivers);

		}

		$list = array();
		if($external)
		{
			
				foreach($datelist as $skey=>$res)
				{
					foreach($external as $key=>$rs)
					{
						if($rs =='高菲菲')continue;

					$upskusql = "";
					$noupsku= "";
					$skuarray = $isupskuarray = "";
					$list[$res['dates']][$rs]["dates"] = $res['dates'];
					$newproductnum = $this->fun->getdatabasesdetail("db_product_develop" ," AND FROM_UNIXTIME(UNIX_TIMESTAMP(linkUrl_addtime),'%Y-%m') ='".$res['dates']."'" , 'count(id) as nums,GROUP_CONCAT(sku) as sku');
					$list[$res['dates']][$rs]["allnewproductnum"] = $newproductnum['nums'];	//总推荐数
					if($newproductnum['sku'])
					{
						$skuarray = explode(",",$newproductnum['sku']);
						$upsku = implode("','",$skuarray);
						if($upsku) $upskusql = " AND sku in('$upsku')";
					}
					$updateproductnum = $this->fun->getdatabasesdetail("db_product_develop_addtime" ," AND createUser ='".$rs."' $upskusql " , 'count(id) as nums,GROUP_CONCAT(sku) as isupsku');
					if($updateproductnum['isupsku'])
					{
						$isupskuarray = explode(",",$updateproductnum['isupsku']);//已经上新的商品
						$lastisupskuarray  = array_unique($isupskuarray);						//去除重,已上新的
						if($skuarray && $isupskuarray)
						{
							$noupsku = array_merge(array_diff($skuarray,$isupskuarray),array_diff($isupskuarray,$skuarray));
							if($noupsku)
								$noupsku = implode(",",$noupsku);
							else
								$noupsku = "";
						}
						
						$needlastsku = implode("','",$lastisupskuarray);
						$avg_made_days = $this->m->getgoodsPublishAnalysis($needlastsku,$rs,$noupsku,$newproductnum['nums']);
					}else{
						//未上架的SKU
						$lastisupskuarray = array();
						$skuarray = explode(",",$newproductnum['sku']);
						$noupsku = implode(",",$skuarray);
					
						$avg_made_days = $this->m->getgoodsPublishAnalysis('noupsku',$rs,$noupsku,$newproductnum['nums']);
					}
					
					//$list[$res['dates']][$rs]["updatesku"] = $newproductnum['sku'];	//需要上新的商品
					//$list[$res['dates']][$rs]["isupsku"] = $updateproductnum['isupsku'];	//已经上新的商品
					$list[$res['dates']][$rs]["noupsku"] = $noupsku;	//还没有上新的商品
					$list[$res['dates']][$rs]["updatenewproductnum"] = count($lastisupskuarray);	//上新数
					$list[$res['dates']][$rs]["avg_made_days"] = $avg_made_days;	//上新数
					
				}
			}
		}
		
		//print_r($list);

		

		$this->tpl->assign("list",$list);
        $this->tpl->display("report/goodsPublishAnalysis.tpl"); 
    }
    
    public function salesShopRank(){
   	    $starttime = $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')+86400):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
        $order_by_data=$this->input->get('orderdata');
        $order_by_data=$order_by_data==''?1:$order_by_data;
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'orderdata'=>$order_by_data);
        
    	//查询开始与结束时间每天的日收入
        $orders=$this->m->getOrderAmountList($starttime,$wherestr,$endtime,"shopname","order_num");
        $shop_ids=iarray_column($orders,'shopid');
        $date_where=$endtime!=''?"dates between '".$starttime."' and '".$endtime."'":"dates='".$starttime."'";
        $fba_order_list =  $this->fun->getdatabaseslist("db_amzordertmp B left join (select sum(costprice) as order_costprice,ordertmpid,
        sum(ordernum) as sell_goods_number from db_amzordertmpsell group by ordertmpid) as A on A.ordertmpid=B.id","$wherestr and {$date_where}
         group by shopid","B.shopname,sum(A.order_costprice) as costprice_total,sum(sell_goods_number) as goods_number_total,B.shopid,sum(B.shipping_fee)
          as shipping_fee_total,SUM(B.goods_amount) as goods_amount_total,sum(shipping_fee) as realfee,sum(payship_fee) as payship_fee_total,
          count(B.id) as order_total",'order by dates desc');
        //echo $this->db->last_query();
        //dump($fba_order_list);
        $new_fba_list=array();
        foreach($fba_order_list as $key=>$val){
            $new_fba_list[$val['shopid']]=$val; 
            if(!in_array($val['shopid'],$shop_ids)){
                $new_info=array('shopid'=>$val['shopid'],'shopname'=>$val['shopname']);
                $orders[]=$new_info;
            }
        }
        //dump($orders);
        $allmaolv=0;
        $good_id_arr=array();
        foreach($orders as $key=>$order){
            $good_id_arr[]=$order['order_id'];
        }

        $good_id_str=implode(',',$good_id_arr);
        if(count($good_id_arr)>0){
            $wherestr.=" and A.order_id in($good_id_str)";
        }
		$shop_orders=array();
        foreach($orders as $key=>$v){
            $v['shipping_fee_total']+=$new_fba_list[$v['shopid']]['shipping_fee_total'];
            $v['goods_amount_total']+=$new_fba_list[$v['shopid']]['goods_amount_total'];
            $v['order_num']+=$new_fba_list[$v['shopid']]['order_total'];
            $v['sell_total']+=$new_fba_list[$v['shopid']]['goods_number_total'];
            $v['costprice_total']+=$new_fba_list[$v['shopid']]['costprice_total'];
            $v['platform_fee_total']-=$new_fba_list[$v['shopid']]['payship_fee_total'];
            
            $v['avg_price']=round(($v['goods_amount_total']+$v['shipping_fee_total'])/$v['order_num'],2);
            $v['order_by_costprice']=$v['costprice_total']+$v['platform_fee_total']+$v['payfee_total']+$v['realexpress_fre'];
            $v['sell_total_money']=$v['goods_amount_total']+$v['shipping_fee_total'];
            $v['order_by_lvrun']=$v['goods_amount_total']+$v['shipping_fee_total']-$v['costprice_total']-$v['platform_fee_total']-$v['payfee_total']-$v['realexpress_fre'];
			if(($v['goods_amount_total']+$v['shipping_fee_total'])>0)
			{
				$v['maoliv']=round(($v['goods_amount_total']+$v['shipping_fee_total']-$v['costprice_total']-$v['platform_fee_total']-$v['payfee_total']-$v['realexpress_fre'])/($v['goods_amount_total']+$v['shipping_fee_total']),4)*100;
			}
            $shop_orders[]=$v;
            $total['goods_amount_total']+=$v['goods_amount_total']+$v['shipping_fee_total'];
            $total['shipping_fee_total']+=$v['shipping_fee_total'];
            $total["costprice_total"]+=$v['costprice_total']+$v['platform_fee_total']+$v['payfee_total']+$v['realexpress_fre'];
            
            $total['shipping_expectfee_total']+=$v['shipping_expectfee_total'];
            $total['platform_fee_total']+=$v['platform_fee_total'];
            $total['order_num']+=$v['order_num'];
            $total['maoliv_avg']+=$v['maoliv_avg'];
            $total['sell_total']+=$v['sell_total'];
        }
        $total['have_total']=$total['goods_amount_total']+$total['shipping_fee_total'];
        $total['give_total']=$total['costprice_total']+$total['platform_fee_total']+$total['payfee_total']+$total['shipping_expectfee_total'];
        $total['maoli_total']=$total['have_total']-$total['give_total'];
        $total['lirun']=$total['goods_amount_total']-$total['costprice_total'];
        $total['lirun_avg']=round(($total['goods_amount_total']-$total['costprice_total'])/$total['goods_amount_total'],4)*100;
        $total['avg_price']=round($total['goods_amount_total']/$total['order_num'],2);
        $tpl_data['tal']=$total;
        
        switch($order_by_data){
            case "1":
                $shop_orders=$this->sort_list($shop_orders,'sell_total_money');
            break;
            case "2":
                $shop_orders=$this->sort_list($shop_orders,'order_num');
            break;
            case "3":
                $shop_orders=$this->sort_list($shop_orders,'sell_total');
            break; 
            case "4":
                $shop_orders=$this->sort_list($shop_orders,'order_by_costprice');
            break; 
            case "5":
                $shop_orders=$this->sort_list($shop_orders,'order_by_lvrun');
            break;      
        
        }

        $tpl_data['list']=$shop_orders;
        $this->tpl->assign($tpl_data);
        $this->tpl->display("report/salesShopRank.tpl"); 
    }
    
    public function salesGoodsRank(){
   	    $starttime =$getstarttime= $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $ordertype=$this->input->get("ordertype");
        $platformID=$this->input->get("platformID");
        $goods_source=$this->input->get("good_source");
        
        $rownum=$this->input->get('rownum');
        $goods_sku=$this->input->get('goods_sku');
        //$rownum=$rownum==0?20:$rownum;
        $ordertype=$ordertype==''?"sell_total":$ordertype;
        $shopid=$this->input->get('shopid');
        $shopname	   = $this->input->get('shopname');
        
        $shopname=trim($shopname,',');
        $can_visit_shop=$this->getViewShops();
        if($can_visit_shop!='isadmin' && $shopname==''){
            if(!empty($getstarttime)){
                $shopname=$can_visit_shop;
            }
        }
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')+86400):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'platformID'=>$platformID,'shopname'=>$shopname,
        'rownum'=>$rownum,'ordertype'=>$ordertype,"goods_sku"=>$goods_sku,'shop_id'=>$shopid,'good_source'=>$goods_source);
        if(!empty($getstarttime)){
            if (count($shopname) >0) {
        	    $shopname=explode(',',$shopname);
        		$whereshop = implode("','",$shopname);
        	}
        	//查询开始与结束时间每天的日收入
            if($whereshop)$wherestr.=" AND shopname in('".$whereshop."')";
            if($goods_sku)$wherestr.=" AND goods_sn like '%".$goods_sku."%'";
            if($goods_source) $wherestr.=" AND g_supplier = ".$goods_source;
            //$wherestr.=" AND goods_sn like '".$goods_source."%'";
            if(!empty($platformID)){
                $wherestr.=" and platformID=$platformID";
            }
             if($rownum==''){$rownum=50000;}
            $retdatas=$this->m->getSaleGoodsRank($starttime,$wherestr,$endtime,$rownum,$ordertype);
            $orders=$retdatas['list'];
            $diff_days=floor((strtotime($endtime)-strtotime($starttime))/86400);
            $allmaolv=0;
            foreach($orders as $key=>$areaorder){
                $good_id_arr[]=$areaorder['goods_id'];
               $goodinfo = $this->fun->getdatabasesdetail("db_goods"," AND goods_id=".$areaorder['goods_id']);
                if($goodinfo){
                    $orders[$key]['goods_name']= $goodinfo['goods_name'];   
                }
                $areaorder['shipping_fee_total']=round($areaorder['shipping_fee_total'],2);
                $areaorder['shipping_expectfee_total']=round($areaorder['shipping_expectfee_total'],2);
                $areaorder['platform_fee_total']=round($areaorder['platform_fee_total'],2);
                $areaorder['payfee_total']=round($areaorder['payfee_total'],2);
                $areaorder["goodsinfo"] = $goodinfo;
                $orders[$key]=$areaorder;
            }
                 
            if(count($good_id_arr)>0){
                $good_id_str=implode(',',$good_id_arr);
                $wherestr.=" and goods_id in($good_id_str)";
            }
            $wherestr=str_replace(" AND g_supplier = ".$goods_source,'',$wherestr);
            $express_list=$this->m->getOrderExpressPirce($starttime,$wherestr,$endtime);
            foreach($orders as $key=>$v){
                foreach($express_list as $good_id_index=>$price){
                    if($good_id_index==$v["goods_id"]){
                        $orders[$key]['realexpress_fre']=$price;
                        $v['realexpress_fre']=$price;
                    } 
                }
                if($diff_days>0){
                    $orders[$key]['day_sales']=round($v['sell_total']/$diff_days,2);    
                }else{
                    $orders[$key]['day_sales']=$v['sell_total'];
                }
                $orders[$key]['maoliv']=@round(($v['goods_amount_total']+$v['shipping_fee_total']-$v['costprice_total']-$v['platform_fee_total']-$v['payfee_total']-$v['realexpress_fre']-$v['shipping_expectfee_total'])/($v['goods_amount_total']+$v['shipping_fee_total']),4)*100;
                $total['goods_amount_total']+=$v['goods_amount_total'];
                $total['shipping_fee_total']+=$v['shipping_fee_total'];
                $total["costprice_total"]+=$v['costprice_total'];
                $total['shipping_expectfee_total']+=$v['shipping_expectfee_total'];
                $total['platform_fee_total']+=$v['platform_fee_total'];
                $total['payfee_total']+=$v['payfee_total'];
                $total['maoliv_avg']+=$v['maoliv_avg'];
                $total['sell_total']+=$v['sell_total'];
            }
            $total['have_total']=$total['goods_amount_total']+$total['shipping_fee_total'];
            $total['give_total']=$total['costprice_total']+$total['platform_fee_total']+$total['payfee_total']+$total['shipping_expectfee_total'];
            $total['maoli_total']=$total['have_total']-$total['give_total'];
            if($total['have_total']>0){
                $total['maoliv_avg']=round($total['maoli_total']/$total['have_total'],4)*100;    
            }
            //if($rownum==50000){$tpl_data['rownum']=$rownum=$retdatas['total'];}
            $total['day_sales']=$diff_days>0?round($total['sell_total']/$diff_days/$rownum,2):$total['sell_total'];
            $tpl_data['total_datas']=$retdatas['total'];
            
            $tpl_data['list']=$orders;
            $tpl_data['total']=$total;
        }else{
            $tpl_data['rownum']=50;
        }
        $factorylist=$this->db->get('db_factory')->result_array();
        $this->tpl->assign('factorylist',$factorylist);
        $this->tpl->assign($tpl_data);
        $this->tpl->assign("platform", $this->fun->getdatabaseslist('db_platform'));//所有平台
        $this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop', " AND del_flag= 0", 'id,name', ' order by name asc')); 
        $this->tpl->display("report/salesGoodsRank.tpl"); 
    }
    
    //单商品销售数据
    public function sellGoodSearch(){
   	    $starttime = $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间      
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
        $sku=$this->input->get('sku');		//结束时间
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'sku'=>$sku);
        if(!empty($sku)){
            //goods_sku
            $goodinfo=$this->fun->getdatabasesdetail("db_goods"," AND goods_sku like '%".$sku."%'");
            if($goodinfo['goods_id']){
                $good_id_str=$goodinfo['goods_id'];
                $wherestr.=" and goods_sn like '%".$sku."%'";
                $sellinfo=$this->m->getGoodSaleInfo($starttime,$wherestr,$endtime);    
            
                $total=array();
                foreach($sellinfo as $key=>$v){
                    $sellinfo[$key]['maoliv']=round(($v['goods_amount_total']-$v['costprice_total'])/($v['goods_amount_total']),4)*100;
                    $total['sell_price_total']+=$v['goods_amount_total'] ;
                    $total['costprice_total']+=$v['costprice_total'];//+$v['platform_fee_total']+$v['payfee_total']+$v['realfee']
                    $total['profit']+=$v['goods_amount_total'] -$v['costprice_total'];
                    $total['order_total']+=$v['order_total'];
                    $total['sell_number_total']+=$v['goods_number_total'];   
                }
            }
        }
        $tpl_data['total']=$total;
        $tpl_data['list']=$sellinfo;
        $this->tpl->assign($tpl_data);
        $this->tpl->display("report/sellGoodSearch.tpl");
    }
    
    public function fbaSellForDay(){
        $pageSize=10000;
   	    $starttime =$getstarttime= $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime; 
        $nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "") $nowpage = 1;  
        $shopname	   = $this->input->get('shopname');
        
        $shopname=trim($shopname,',');
        $can_visit_shop=$this->getViewShops();
        if($can_visit_shop!='isadmin' && $shopname==''){
            if(!empty($getstarttime)){
                $shopname=$can_visit_shop;
            }
        }
        
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'shopname'=>$shopname);
        
    	if (count($shopname) >0) {
    	    $shopname=explode(',',$shopname);
    		$whereshop = implode("','",$shopname);
            $shopinfo=$this->fun->getdatabasesdetail('d_shop', " AND name='$shopname[0]'", 'id,name');
    	}
        
        if($whereshop)$wherestr=" AND shopname in('".$whereshop."')";
        
        if(!empty($getstarttime)){
            if($starttime!='' or $endtime!=''){
                $shop_where=$endtime!=''?"and dates between '".$starttime."' and '".$endtime."'":"and dates='".$starttime."'";
            }
            $this->tpl->assign("d_shop", $this->fun->getdatabaseslist('db_amzordertmp', $shop_where." and shopid>0", 'distinct shopname as name,shopid as id', ' order by id asc')); 
    
            $result=$this->m->getFBAorders($starttime,$wherestr,$endtime,$nowpage);
            if(count($result['list'])>0){
                foreach($result['list'] as $key=>$res){
                    $result['list'][$key]['lvrun']=round($res['goods_amount_total']+$res['realfee']
                    -$res['costprice_total']+$res['payship_fee_total']-$res['ship_price'],2);
                    
                }
            }
            
            $total_arr=array(); 
    
            $total_arr=$result['total_data'][0];
            $total_arr["i_total"]=$total_arr["goods_amount_total"]+$total_arr["realfee"];
            $total_arr["lirun"]+=$total_arr['goods_amount_total']+$total_arr['realfee']-$total_arr['costprice_total']-$total_arr['ship_price_total']+$total_arr['payship_fee_total'];
            $tpl_data['tal']=$total_arr;
            $tpl_data['list']=$result['list'];
            $tpl_data['imgdata']=array_reverse($result['list']);//array_slice($result['list'],0,30);
    		$pageList = $this->pagenav->page($result["total"], $nowpage, $pageSize);
            $this->tpl->assign("totalpage", ceil($result["total"] / $pageSize));
    		$this->tpl->assign("total", $result["total"]);
            $this->tpl->assign("pageList", $pageList);
        }
        
        
       //echo $this->db->last_query();
        $this->tpl->assign("shopsid", $shopinfo['id']);
        $this->tpl->assign($tpl_data);
        $this->tpl->display("report/fbaSellForDay.tpl");   
        //dump($orderlist); 
    }
    
    public function fbaGoodsRank(){
        
        $starttime = $getstarttime = $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $ordertype=$this->input->get("ordertype");
        $skunumber=$this->input->get("skunumber");
        $rownum=$this->input->get('rownum');
        //$rownum=$rownum==0?50:$rownum;
        $ordertype=$ordertype==''?"sell_total":$ordertype;
        
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
        $shopname	   = $this->input->get('shopname');
        $shopname=trim($shopname,',');
        $can_visit_shop=$this->getViewShops();
        if($can_visit_shop!='isadmin' && $shopname==''){
            if(!empty($getstarttime)){
                $shopname=$can_visit_shop;
            }
        }
        
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'shopname'=>$shopname,'rownum'=>$rownum,'ordertype'=>$ordertype,'skunumber'=>$skunumber);
        if(!empty($getstarttime)){
            //查询开始与结束时间每天的日收入
            $whereshop=str_replace(',',"','",$shopname);
            if($shopname)$wherestr=" AND shopname in('".$whereshop."')";
    
            if($skunumber)$wherestr.=" AND productid like '%{$skunumber}%'";
            if($rownum==''){$rownum=50000;}
            $retdata=$this->m->getFbaGoodsRank($starttime,$wherestr,$endtime,$rownum,$ordertype);
            $orders=$retdata['list'];
            $diff_days=floor((strtotime($endtime)-strtotime($starttime))/86400);
            $allmaolv=0;
            foreach($orders as $key=>$areaorder){
                $good_id_arr[]=$areaorder['goods_id'];
                $costprice=0;
               $goodinfo = $this->fun->getdatabasesdetail("db_goods"," AND goods_id=".$areaorder['goods_id']);
                if($goodinfo){
                    $orders[$key]['goods_name']= $goodinfo['goods_name'];   
                }
                //计算成本
                $costprice=$this->fun->get_Goods_costprice($areaorder['productid']);
                if($costprice>0){
                    $orders[$key]['costprice_total']=$areaorder['sell_total']*$costprice;    
                }
                $orders[$key]["goodsinfo"] = $goodinfo;
            }
            if(count($good_id_arr)>0){
                $good_id_str=implode(',',$good_id_arr);
                $wherestr.=" and goods_id in($good_id_str)";
            }
            $express_list=$this->m->getOrderExpressPirce($starttime,$wherestr,$endtime);
            $goods_amount_total=$costprice_total=$sell_total=0;
            foreach($orders as $key=>$v){
                foreach($express_list as $good_id_index=>$price){
                    if($good_id_index==$v["goods_id"]){
                        $orders[$key]['realexpress_fre']=$price;
                        $v['realexpress_fre']=$price;
                    } 
                }
                $diff_days=$diff_days==0?1:$diff_days;
                $orders[$key]['day_sales']=round($v['sell_total']/$diff_days,2);
                $orders[$key]['maoliv']=round(($v['goods_amount_total']-$v['costprice_total']+$v['payship_fee_total']-$v['firstshipment_fre'])/($v['goods_amount_total']),4)*100;
                $goods_amount_total+=$v['goods_amount_total'];
                $maoli_total+=$v['goods_amount_total']-$v['costprice_total']+$v['payship_fee_total']-$v['firstshipment_fre'];
                $costprice_total+=$v['costprice_total'];
                $sell_total+=$v['sell_total'];
                 $orders[$key]['lirun']=number_format($v['goods_amount_total']-$v['costprice_total']+$v['payship_fee_total']-$v['firstshipment_fre'],2); 
                $orders[$key]['costprice_total']=number_format($v['costprice_total'],2);  
                $orders[$key]['goods_amount_total']=number_format($v['goods_amount_total'],2);
                $ship_fba_pay+= $v['payship_fee_total'];
                $vfirstshipment_fre+=$v['firstshipment_fre'];$total_day_sales+= $orders[$key]['day_sales'];
            }
            
            if($goods_amount_total)        $all_lirunlv=round($maoli_total/$goods_amount_total,3)*100;
            $tpl_data['total_datas']=$retdata['total'];
            if($rownum==50000){$tpl_data['rownum']=$retdata['total'];}
            $tpl_data['data_total']=array('sell_total'=>$sell_total,'costprice_total'=>$costprice_total,
            'maoli_total'=>$maoli_total,'day_sales'=>$total_day_sales,
            'goods_amount_total'=>$goods_amount_total,'all_lirunlv'=>$all_lirunlv,'ship_fba_pay'=>$ship_fba_pay,'firstshipment_fre'=>$vfirstshipment_fre);
            $tpl_data['list']=$orders;
        }else{
            $tpl_data['rownum']=50;
        }
    	
        $this->tpl->assign($tpl_data);
        
        $this->tpl->display("report/fbaGoodsRank.tpl");            
    }
    
    public function fbaSellForMonth(){
        
        $this->tpl->display("report/fbaSellForMonth.tpl");    
    }
    
    public function dayShipMent(){
        $this->tpl->display("report/dayShipMent.tpl");    
    }
    
    //退款统计
    public function orderRefund(){
        //d_shop
        $starttime = $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $orderbydata=$this->input->get("orderdata");
        $platformID=$this->input->get("platformID");
        $timetype=$this->input->get("timetype");
        $shopname	   = $this->input->get('shopname');
        $shopname=trim($shopname,',');
        $can_visit_shop=$this->getViewShops();
        if($can_visit_shop!='isadmin' && $shopname==''){
            if(!empty($getstarttime)){
                $shopname=$can_visit_shop;
            }
        }
        
        $timetype=$timetype==''?2:$timetype;
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')+86400):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'orderdata'=>$orderbydata,'shopname'=>$shopname,
        'platformID'=>$platformID,'timetype'=>$timetype);
        if (count($shopname) >0) {
    	    $shopname=explode(',',$shopname);
    		$whereshop = implode("','",$shopname);
    	}
        if($whereshop)$wherestr=" AND pr.shopname in('".$whereshop."')";
        if($whereshop)$amazonwhere=$shop_where=" AND shopname in('".$whereshop."')";
        
        if($whereshop)$wish_where=" AND A.shopname in('".$whereshop."')";
        $starttime=trim($starttime)." 00:00:00";
        $endtime=trim($endtime)." 23:59:59";
        $order_date_where=$endtime!=''?"dates between '".$starttime."' and '".$endtime."'":"dates='".$starttime."'";
        $refund_where=$order_date_where;
        $all_date_where=$order_date_where;
        $data_colnum=$timetype==1?'ordertime':'report_time';
        $amazon_date_where=$endtime!=''?"$data_colnum between '".$starttime."' and '".$endtime."'":"$data_colnum='".$starttime."'";
        
        if($timetype==2){
            $starttime=strtotime($starttime);
            $endtime=strtotime($endtime);
            $refund_where=$endtime!=''?"pr.refund_time between '".$starttime."' and '".$endtime."'":"pr.refund_time='".$starttime."'";
            $last_starttime=date("Y-m-d H:i:s",strtotime('-1 month',$starttime));
            $last_endtime=date("Y-m-d H:i:s",strtotime('-1 month',$endtime));
            //$last_endtime=
            //总订单的统计时间推前一个月
            $all_date_where=$endtime!=''?"dates between '".$last_starttime."' and '".$last_endtime."'":"dates='".$last_starttime."'";    
        }
        $column="pr.shop_id";    
        $wherestr.=" and pr.order_sn=ol.order_sn";
        if(!empty($platformID)){
            $wherestr.=" and ol.platformID=$platformID";
            $wish_where=" and B.platformID=$platformID";
        }
        $ebay_refundlist=$this->fun->getdatabaseslist("db_paypal_refund as pr,
         db_order_list as ol","$wherestr and $refund_where AND refund_status>2 group by $column","pr.shop_id as shopid,ol.shopname,SUM(pr.refund_money * ol.moneyrate) as goods_amount_total,count(*) as order_num"," order by order_num desc");
      // echo $this->db->last_query();
        $amazon_refundlist=$this->fun->getdatabaseslist("db_amzordertmp_cancel","$amazonwhere and  {$amazon_date_where}
          group by shopid","count(*) as order_num,shopid,shopname,SUM(RMBmoney+shipping_fee+RMBrefundmoney) as goods_amount_total");
        $new_datalist=array_merge($ebay_refundlist,$amazon_refundlist);
        ///dump($amazon_refundlist);
        //dump($ebay_refundlist);
       // echo $this->db->last_query();
        $tys =$timetype==1?"ordertime":"Refund_Date";   
        if ($starttime) {
            if($timetype==2){
                $starttime=date('Y-m-d H:i:s',$starttime);    
            }
            $wish_where .= " AND ($tys >= '" . $starttime . "')";
        }
        if ($endtime) {
            if($timetype==2){
                $endtime=date('Y-m-d H:i:s',$endtime);    
            }
            $wish_where .= " AND ($tys <= '" . $endtime . "')";
        }
        $wish_refund_list = $this->fun->getdatabaseslist("db_wish_refund A LEFT JOIN db_order_list B on A.order_id = B.order_id",$wish_where,
         "count(*) as order_num,A.shopid,A.shopname,SUM(Refund_Amount_Rmb) as goods_amount_total"," group by shopname");
       // echo $this->db->last_query(); 
        //dump($wish_refund_list);
        //dump($new_datalist);

        $new_datalist=array_merge($new_datalist,$wish_refund_list); 
        if($platformID==0){
            $orders=$new_datalist;
        }elseif($platformID==2){
            $orders=$amazon_refundlist;   
        }elseif($platformID==16){
            $orders=$wish_refund_list;   
        }
          
        $shopids=iarray_column($orders,'shopid');
        //echo $this->db->last_query();
        $shopids[]=0;
        $shopids_id_str=implode(",",$shopids);
        $orderwhere=$shop_where;
        $costpriceData=$this->fun->getdatabaseslist("db_order_list","$shop_where and  {$all_date_where} AND
         order_status !=6 AND order_status !=7 group by db_order_list.shopid","count(*) as order_num,shopid,SUM(goods_amount) as goods_amount_total");
        $orderlist=array();
        foreach($costpriceData as $key=>$val){
            $orderlist[$val['shopid']]=$val;
        }
        $datalist=array();
        $all_num_mod=$refund_num_money=0;
          
        foreach($orders as $key=>$val){
            $val['goods_amount_total']=round(abs($val['goods_amount_total']),2);
            if($orderlist[$val['shopid']]['order_num']){
                 $val['num_mod']=round($val['order_num']/$orderlist[$val['shopid']]['order_num'],3)*100;
                 if($orderlist[$val['shopid']]['goods_amount_total']!=0){
                 $val['amount_mod']=round($val['goods_amount_total']/$orderlist[$val['shopid']]['goods_amount_total'],3)*100;   
                 }
                  
            }
            $all_num_mod+=$val['order_num']; 
            $refund_num_money+=$val['goods_amount_total']; 
            //dump($val['order_num']);
            $val['all_order_num']=$orderlist[$val['shopid']]['order_num'];
            $val['amount_total']=$orderlist[$val['shopid']]['goods_amount_total'];
            $datalist[]=$val;
            $allsubtotal+=$val['all_order_num'];
            $allcosprice+=$val['amount_total']; 
        }
        $tpl_data['allsubtotal']=$allsubtotal;
        $tpl_data['allcosprice']=$allcosprice;
        $tpl_data['refund_num']=$all_num_mod;
        $tpl_data['refund_num_money']=$refund_num_money;//sss
        if($allsubtotal!=0){
            $tpl_data['refund_num_mod']=round($all_num_mod/$allsubtotal,3)*100;
            $tpl_data['refund_num_money_mod']=round($refund_num_money/$allcosprice,3)*100;    
        }
        
        if($orderbydata==1){
            $datalist=$this->sort_list($datalist,'num_mod');    
        }
        $tpl_data['shop_refundlist']=$datalist;
        
//country
      
            $orders=$this->fun->getdatabaseslist("db_paypal_refund as pr,
             db_order_list as ol","$wherestr and $order_date_where AND refund_status>2 group by ol.country_cn","ol.country_cn as shopid,ol.country,ol.country_code,
             ol.shopname,SUM(pr.refund_money * ol.moneyrate) as goods_amount_total,count(*) as order_num"," order by order_num desc");
            //echo $this->db->last_query();
            
            //wish_refund list
            $wish_country_refund = $this->fun->getdatabaseslist("db_wish_refund A LEFT JOIN db_order_list B on A.order_id = B.order_id",$wish_where,
            "count(*) as order_num,B.country_cn as shopid,B.country,B.country_code,A.shopname,SUM(Refund_Amount_Rmb) as goods_amount_total"," group by B.country_cn order by order_num desc");
            $orders=array_merge($orders,$wish_country_refund); 
            //$shopids=iarray_column($orders,'shopid');
            

        $all_countrys=iarray_column($orders,'shopid');
        $all_countrys[]='0';
        //amazon refund list
        $amzorder_country_orders=$this->fun->getdatabaseslist("db_amzordertmp_cancel","$amazonwhere and  {$amazon_date_where}
        group by country_cn","count(*) as order_num,shopname,SUM(RMBmoney+shipping_fee+RMBrefundmoney) as goods_amount_total,
        country_cn as shopid");
        //$shopids=iarray_column($orders,'shopid');
        
        $orders=array_merge($orders,$amzorder_country_orders); 
        $shopids=iarray_column($orders,'shopid');
        
        $new_orders=array();
        foreach($orders as $index=>$info){
            $info['goods_amount_total']=abs($info['goods_amount_total']);
            if(!empty($info['country'])){
                $new_orders[$info['shopid']]['country']=$info['country'];    
            }
            $new_orders[$info['shopid']]['shopid']=$info['shopid'];
            $new_orders[$info['shopid']]['order_num']+=$info['order_num'];
            $new_orders[$info['shopid']]['goods_amount_total']+=$info['goods_amount_total'];
            
        }
        $orders=$new_orders;
        
        $shopids_id_str=implode("','",$shopids);
        $orderwhere=" and country_cn in('$shopids_id_str') ";
        $costpriceData=$this->fun->getdatabaseslist("db_order_list","$shop_where $orderwhere and  {$all_date_where} AND
         order_status !=6 AND order_status !=7 group by db_order_list.country_cn","count(*) as order_num,country_cn as shopid,SUM(goods_amount) as goods_amount_total");
        $orderlist=array();
        foreach($costpriceData as $key=>$val){
            $orderlist[$val['shopid']]=$val;
        }
        $datalist=array();
        $all_num_mod=$refund_num_money=0;
        foreach($orders as $key=>$val){
            $val['goods_amount_total']=round($val['goods_amount_total'],2);
            if($orderlist[$val['shopid']]['order_num']){
             $val['num_mod']=round($val['order_num']/$orderlist[$val['shopid']]['order_num'],3)*100;
            $val['amount_mod']=round($val['goods_amount_total']/$orderlist[$val['shopid']]['goods_amount_total'],3)*100;   
            }
            $val['all_order_num']=$orderlist[$val['shopid']]['order_num'];
            $val['amount_total']=$orderlist[$val['shopid']]['goods_amount_total'];
            //$val['shopid']=$orderlist[$val['shopid']]['shopid'];
            $datalist[]=$val;
            $allsubtotal1+=$val['all_order_num'];
            $allcosprice1+=$val['amount_total']; 
            $all_num_mod+=$val['order_num']; 
            $refund_num_money+=$val['goods_amount_total']; 
        }
        $tpl_data['allsubtotal1']=$allsubtotal1;
        $tpl_data['allcosprice1']=$allcosprice1;
        $tpl_data['refund_num1']=$all_num_mod;
        $tpl_data['refund_num_money1']=$refund_num_money;
        if($allsubtotal1!=0){
            $tpl_data['refund_num_mod1']=round($all_num_mod/$allsubtotal1,3)*100;
            $tpl_data['refund_num_money_mod1']=round($refund_num_money/$allcosprice1,3)*100;
        }
        
        if($orderbydata==1){
            $datalist=$this->sort_list($datalist,'num_mod');    
        }
        $tpl_data['country_refundlist']=$datalist;
        
//question
        $orders=$this->fun->getdatabaseslist("db_paypal_refund as pr,
         db_order_list as ol","$wherestr and $order_date_where AND refund_status>2 group by pr.refund_reason",
         "ol.country_cn as shopid,pr.refund_reason,ol.country,ol.country_code,ol.shopname,SUM(pr.refund_money * ol.moneyrate)
          as goods_amount_total,count(*) as order_num"," order by order_num desc limit 20");
        //refund_num_mod refund_num_money_mod
        $wish_question_refund = $this->fun->getdatabaseslist("db_wish_refund A LEFT JOIN db_order_list B on A.order_id = B.order_id",$wish_where,
            "count(*) as order_num,B.country_cn as shopid,A.refund_reason as refund_reason, B.country,B.country_code,A.shopname,SUM(Refund_Amount_Rmb) as goods_amount_total",
            " group by A.Refund_Reason order by order_num desc");
            $orders=array_merge($orders,$wish_question_refund); 
          
        $shopids=iarray_column($orders,'shopid');
        $shopids_id_str=implode("','",$shopids);
        $costpriceData=$this->fun->getdatabaseslist("db_order_list"," and  {$all_date_where} AND
         order_status !=6 AND order_status !=7 ","count(*) as order_num,country_cn as shopid,SUM(goods_amount) as goods_amount_total");
         //dump($costpriceData);

        $orderlist=array();
        foreach($costpriceData as $key=>$val){
            $orderlist[]=$val;
        }
        $datalist=array();
        foreach($orders as $key=>$val){
            $val['goods_amount_total']=round($val['goods_amount_total'],2);
            $val['shopid']=0;
            if($all_num_mod){
               $val['num_mod']=round($val['order_num']/$all_num_mod,3)*100;
               $val['amount_mod']=round($val['goods_amount_total']/$refund_num_money,3)*100;   
            }        
            $datalist[]=$val;
        }
        $this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop', " AND del_flag= 0", 'id,name', ' order by name asc')); 
        if($orderbydata==1){
            $datalist=$this->sort_list($datalist,'num_mod');    
        }
        $tpl_data['question_refundlist']=$datalist;
        $this->tpl->assign("platform", $this->fun->getdatabaseslist('db_platform'));//所有平台
        $this->tpl->assign($tpl_data);  
        $this->tpl->display("report/orderRefund.tpl");
    }
    
    public function fbaRefund(){
        
        $starttime = $getstarttime= $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $orderbydata=$this->input->get("orderdata");
        $countType=$this->input->get("countType");
        $goods_sku=$this->input->get("goods_sku");
        $timetype=$this->input->get("timetype");
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')+86400):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
        $orderbydata=$orderbydata==''?1:$orderbydata;
        $timetype=$timetype==''?3:$timetype;
        $starttime=trim($starttime);
        $shopname	   = $this->input->get('shopname');
        
        $can_visit_shop=$this->getViewShops();
        if($can_visit_shop!='isadmin' && $shopname==''){
            if(!empty($getstarttime)){
                $shopname=$can_visit_shop;
            }
        }
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'orderdata'=>$orderbydata,'countType'=>$countType,'goods_sku'=>$goods_sku,'timetype'=>$timetype,'shopname'=>$shopname);
        if (count($shopname) >0) {
    	    $shopname=explode(',',$shopname);
    		$whereshop = implode("','",$shopname);
    	}
        if($whereshop)$wherestr=" AND B.shopname in('".$whereshop."')";
        
        if(!empty($getstarttime)){
            //echo $starttime."222";
            $endtime=trim($endtime);
            
            $endtime.=" 23:59:59";
            $starttime.=" 00:00:00";
            $date_where=$endtime!=''?"dates between '".$starttime."' and '".$endtime."'":"dates='".$starttime."'";
            $wherestr.=' and A.amazon_id is not null';
            if($timetype==1){
                 $date_where=$endtime!=''?"ordercreatetime between '".$starttime."' and '".$endtime."'":"ordercreatetime='".$starttime."'";
            }
            $all_orderinfo_where=$date_where;
            if($timetype==3){
                 $refund_date_where=$endtime!=''?" where refund_time between '".$starttime."' and '".$endtime."'":"where refund_time='".$starttime."'";
                 $date_where="1=1";
            }
    
            if($countType!='goods'){//按店铺退款统计
                
                $datalist=$this->fun->getdatabaseslist("db_amzordertmp B left join (select count(*) as
                 goods_total,amazon_id from db_amzordertmp_refund $refund_date_where group by amazon_id) as A on A.amazon_id=B.id","$wherestr and {$date_where} group by B.shopid",
                 'SUM(B.moneyrate * B.refundMoney) as refund_total,shopid as sku,shopname,amazon_id,count(*) as order_num,SUM(goods_total) as goods_num');
                $shopids=iarray_column($datalist,'sku');
                    //dump($this->db->last_query());
                $shopids_id_str=implode("','",$shopids);
                $orderwhere=" and shopid in('$shopids_id_str') ";
                $all_orderinfo=$this->fun->getdatabaseslist("db_amzordertmp","$orderwhere and  {$all_orderinfo_where} 
                  group by sku","count(*) as order_num,shopid as sku,SUM(goods_amount+shipping_fee) as goods_amount_total");
                $orderlist=array();
                foreach($all_orderinfo as $key=>$val){
                    $orderlist[$val['sku']]=$val;
                }
           }else{
                if(empty($goods_sku)){
                    if($timetype==3){
                        $refund_date_where=$endtime!=''?" A.refund_time between '".$starttime."' and '".$endtime."'":" A.refund_time='".$starttime."'";    
                    }else{
                        $refund_date_where=$date_where;    
                    }
                    $datalist=$this->fun->getdatabaseslist("db_amzordertmp_refund A left join db_amzordertmp as B on A.amazon_id=B.id","$wherestr and {$refund_date_where} group by A.sku",
                     'SUM(B.moneyrate * B.refundMoney) as refund_total,B.shopid,B.shopname,amazon_id,count(*) as order_num,sku'," order by order_num desc");
                    $sku_list=iarray_column($datalist,'sku');
                    $sku_id_str=implode("','",$sku_list);
                    $orderwhere="and db_amzordertmpsell.ordertmpid=db_amzordertmp.id and productid in('$sku_id_str') ";
                }else{
                    $orderwhere="and db_amzordertmpsell.ordertmpid=db_amzordertmp.id and productid like'%$goods_sku%'";    
                }
                //echo $this->db->last_query();
                $all_orderinfo=$this->fun->getdatabaseslist("db_amzordertmp,db_amzordertmpsell","$orderwhere and  {$date_where} 
                  group by productid","count(*) as order_num,productname,db_amzordertmp.shopid,productid,SUM(db_amzordertmpsell.goods_amount+shipping_fee) as goods_amount_total");
    
                if(!empty($goods_sku)){
                    $sku_list=iarray_column($all_orderinfo,'productid');
                    $sku_id_str=implode("','",$sku_list);
                    $wherestr.=" and A.sku in('$sku_id_str')";
                    $datalist=$this->fun->getdatabaseslist("db_amzordertmp_refund A left join db_amzordertmp as B on A.amazon_id=B.id","$wherestr and {$date_where} group by A.sku",
                     'SUM(B.moneyrate * B.refundMoney) as refund_total,B.shopid,B.shopname,amazon_id,count(*) as order_num,sku'," order by order_num desc limit 40");
                }
                  
                $orderlist=array();
                //echo $this->db->last_query();
                foreach($all_orderinfo as $key=>$val){
                    $orderlist[$val['productid']]=$val;
                }
           }     
              
            foreach($datalist as $key=>$val){
                $val['goods_name']=$orderlist[$val['sku']]['productname'];
                $val['refund_total']=round($val['refund_total'],2);
                $val['all_order_num']=$orderlist[$val['sku']]['order_num'];  
                $val['amount_total']=round($orderlist[$val['sku']]['goods_amount_total'],2); 
                if($val['all_order_num']){
                     $val['num_mod']=round($val['order_num']/$orderlist[$val['sku']]['order_num'],4)*100;
                     $val['amount_mod']=round(abs($val['refund_total'])/$orderlist[$val['sku']]['goods_amount_total'],4)*100; 
                }
                $allsubtotal+=$val['all_order_num'];
                $allcosprice+=$val['amount_total']; 
                $all_num_mod+=$val['order_num']; 
                $refund_num_money+=$val['refund_total']; 
                $datalist[$key]=$val;
            }
            
            
            $tpl_data['allsubtotal']=$allsubtotal;
            $tpl_data['allcosprice']=$allcosprice;
            $tpl_data['refund_num']=$all_num_mod;
            $tpl_data['refund_num_money']=$refund_num_money;
      
            if($allsubtotal!=0){
                $tpl_data['refund_num_mod']=round($all_num_mod/$allsubtotal,3)*100;
                $tpl_data['refund_num_money_mod']=round(abs($refund_num_money)/$allcosprice,3)*100;
            }
            
            switch($orderbydata){
                case "1":
                    $datalist=$this->sort_list($datalist,'order_num');
                break;
                case "2":
                    $datalist=$this->sort_list($datalist,'refund_total','asc');
                break;
                case "3":
                    $datalist=$this->sort_list($datalist,'amount_mod');
                break;
                case "4":
                    $datalist=$this->sort_list($datalist,'num_mod');
                break;
            }
            $tpl_data['shop_refundlist']=$datalist;
        }
        
        $this->tpl->assign($tpl_data);  
        $this->tpl->display("report/fbaRefund.tpl");     
    }
    
    public function fbaShopSells(){
        // FBA订单日报表┊ FBA商品报表┊ FBA退款统计┊ FBA库存报表
        $starttime = $this->input->get('starttime');	//开始时间
        $endtime   = $this->input->get('endtime');		//结束时间
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')+86400):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
        $shopname	   = $this->input->get('shopname');
        $shopname=trim($shopname,',');
        $whereshop=str_replace(',',"','",$shopname);
        
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'end_month'=>$end_month,'shopname'=>$shopname,);
        
        if($shopname){
            //FBA销售报表
            if($shopname)$wherestr=" AND shopname in('".$whereshop."')";
            $retdatas=$this->m->getFbaGoodsRank($starttime,$wherestr,$endtime,200);
            $goods_sales=$retdatas['list'];
            $diff_days=floor((strtotime($endtime)-strtotime($starttime))/86400);
            $allmaolv=0;
            $orders=$goods_sales;
        
            if($shopname)$wherestr=" AND shopname in('".$whereshop."')";
            //FBA订单日报表
            $result=$this->m->getFBAorders($starttime,$wherestr,$endtime,$nowpage);
            $day_sales=$result['list'];
            $total_arr=array(); 
            $total_arr=$result['total_data'][0];
            $total_arr["i_total"]=$total_arr["goods_amount_total"]+$total_arr["realfee"];
            $total_arr["lirun"]+=$total_arr['goods_amount_total']+$total_arr['realfee']-$total_arr['ship_price_total']-$total_arr['costprice_total']+$total_arr['payship_fee_total'];
            
        
       
            $goods_id_list=iarray_column($orders,"goods_id");
            $goods_id_str=implode(',',$goods_id_list);
            if(count($goods_id_list)>0)$goods_wherestr=" AND goods_id in(".$goods_id_str.")";
            $goods_list=$this->fun->getdatabaseslist("db_goods"," $goods_wherestr","*");
            $goods_list=iarray_column($goods_list,"goods_name","goods_id");
            foreach($orders as $key=>$areaorder){
                $good_id_arr[]=$areaorder['goods_id'];
                $costprice=0;
                
                $orders[$key]['goods_name']= $goods_list[$areaorder['goods_id']];   
                
                //计算成本
                $costprice=$this->fun->get_Goods_costprice($areaorder['productid']);
                if($costprice>0){
                    $orders[$key]['costprice_total']=$areaorder['sell_total']*$costprice;    
                }
                $orders[$key]["goodsinfo"] = $goodinfo;
            }
            if(count($good_id_arr)>0){
                $good_id_str=implode(',',$good_id_arr);
                $wherestr.=" and goods_id in($good_id_str)";
            }
            $express_list=$this->m->getOrderExpressPirce($starttime,$wherestr,$endtime);
            $goods_amount_total=$costprice_total=$sell_total=$goodsday_sales=0;
            foreach($orders as $key=>$v){
                foreach($express_list as $good_id_index=>$price){
                    if($good_id_index==$v["goods_id"]){
                        $orders[$key]['realexpress_fre']=$price;
                        $v['realexpress_fre']=$price;
                    } 
                }
                $orders[$key]['day_sales']=round($v['sell_total']/$diff_days,2);
                $orders[$key]['maoliv']=round(($v['goods_amount_total']-$v['costprice_total']+$v['payship_fee_total']-$v['firstshipment_fre'])/($v['goods_amount_total']),4)*100;
                $goods_amount_total+=$v['goods_amount_total'];
                $maoli_total+=$v['goods_amount_total']-$v['costprice_total']+$v['payship_fee_total']-$v['firstshipment_fre'];
                $costprice_total+=$v['costprice_total'];
                $sell_total+=$v['sell_total'];
                 $orders[$key]['lirun']=number_format($v['goods_amount_total']-$v['costprice_total']+$v['payship_fee_total']-$v['firstshipment_fre'],2); 
                $orders[$key]['costprice_total']=number_format($v['costprice_total'],2);  
                $orders[$key]['goods_amount_total']=number_format($v['goods_amount_total'],2);
                $goodsday_sales+=$orders[$key]['day_sales'];
                $ship_fba_pay+= $v['payship_fee_total'];
                $vfirstshipment_fre+=$v['firstshipment_fre'];
            }
            if($goods_amount_total)        $all_lirunlv=round($maoli_total/$goods_amount_total,3)*100;
            //allsubzhic
            
            
            $tpl_data['goods_sales']=$orders;
            $tpl_data['data_total']=array('sell_total'=>$sell_total,'costprice_total'=>$costprice_total,'day_sales'=>$goodsday_sales,
            'maoli_total'=>$maoli_total,'goods_amount_total'=>$goods_amount_total,'all_lirunlv'=>$all_lirunlv,'ship_fba_pay'=>$ship_fba_pay,'firstshipment_fre'=>$vfirstshipment_fre);
            if($total_arr['goods_amount_total']+$total_arr['realfee']>0){
                $total_arr["lirunlv"]=round($total_arr["lirun"] /($total_arr['goods_amount_total']+$total_arr['realfee'])*100,2);   
            }
            $tpl_data['tal']=$total_arr;//单日销售统计
            $tpl_data['day_sales']=$day_sales;
            
            //直发退款列表
            if($whereshop)$wherestr=" AND pr.shopname in('".$whereshop."')";
            if($whereshop)$amazonwhere=$shop_where=" AND shopname in('".$whereshop."')";
            
            if($whereshop)$wish_where=" AND A.shopname in('".$whereshop."')";
            $starttime=trim($starttime)." 00:00:00";
            $endtime=trim($endtime)." 23:59:59";
            $order_date_where=$endtime!=''?"dates between '".$starttime."' and '".$endtime."'":"dates='".$starttime."'";
            $refund_where=$order_date_where;
            $all_date_where=$order_date_where;
            $data_colnum=$timetype==1?'ordertime':'report_time';
            $amazon_date_where=$endtime!=''?"$data_colnum between '".$starttime."' and '".$endtime."'":"$data_colnum='".$starttime."'";
            
            if($timetype==2){
                $starttime=strtotime($starttime);
                $endtime=strtotime($endtime);
                $refund_where=$endtime!=''?"pr.refund_time between '".$starttime."' and '".$endtime."'":"pr.refund_time='".$starttime."'";
                $last_starttime=date("Y-m-d H:i:s",strtotime('-1 month',$starttime));
                $last_endtime=date("Y-m-d H:i:s",strtotime('-1 month',$endtime));
                //$last_endtime=
                //总订单的统计时间推前一个月
                $all_date_where=$endtime!=''?"dates between '".$last_starttime."' and '".$last_endtime."'":"dates='".$last_starttime."'";    
            }
            $column="pr.shop_id";    
            $wherestr.=" and pr.order_sn=ol.order_sn";
            if(!empty($platformID)){
                $wherestr.=" and ol.platformID=$platformID";
                $wish_where=" and B.platformID=$platformID";
            }
            $ebay_refundlist=$this->fun->getdatabaseslist("db_paypal_refund as pr,
             db_order_list as ol","$wherestr and $refund_where AND refund_status>2 group by $column","pr.shop_id as shopid,ol.shopname,SUM(pr.refund_money * ol.moneyrate) as goods_amount_total,count(*) as order_num"," order by order_num desc");
           //echo $this->db->last_query();
            $amazon_refundlist=$this->fun->getdatabaseslist("db_amzordertmp_cancel","$amazonwhere and  {$amazon_date_where}
              group by shopid","count(*) as order_num,shopid,shopname,SUM(RMBmoney+shipping_fee+RMBrefundmoney) as goods_amount_total");
            $new_datalist=array_merge($ebay_refundlist,$amazon_refundlist);
           // echo $this->db->last_query();
            
            $tys =$timetype==1?"ordertime":"Refund_Date";   
            if ($starttime) {
                if($timetype==2){
                    $starttime=date('Y-m-d H:i:s',$starttime);    
                }
                $wish_where .= " AND ($tys >= '" . $starttime . "')";
            }
            if ($endtime) {
                if($timetype==2){
                    $endtime=date('Y-m-d H:i:s',$endtime);    
                }
                $wish_where .= " AND ($tys <= '" . $endtime . "')";
            }
            $wish_refund_list = $this->fun->getdatabaseslist("db_wish_refund A LEFT JOIN db_order_list B on A.order_id = B.order_id",$wish_where,
             "count(*) as order_num,A.shopid,A.shopname,SUM(Refund_Amount_Rmb) as goods_amount_total"," group by shopname");
            $new_datalist=array_merge($new_datalist,$wish_refund_list); 
            //echo $this->db->last_query();
            $shopids=iarray_column($new_datalist,'shopid');
            //echo $this->db->last_query();
            $shopids[]=0;
            $shopids_id_str=implode(",",$shopids);
            $orderwhere=$shop_where;
            $costpriceData=$this->fun->getdatabaseslist("db_order_list","$shop_where and  {$all_date_where} AND
             order_status !=6 AND order_status !=7 group by db_order_list.shopid","count(*) as order_num,shopid,SUM(goods_amount) as goods_amount_total");
            $orderlist=array();
            foreach($costpriceData as $key=>$val){
                $orderlist[$val['shopid']]=$val;
            }
            $datalist=array();
            $all_num_mod=$refund_num_money=0;
              
            foreach($new_datalist as $key=>$val){
                $val['goods_amount_total']=round(abs($val['goods_amount_total']),2);
                if($orderlist[$val['shopid']]['order_num']){
                     $val['num_mod']=round($val['order_num']/$orderlist[$val['shopid']]['order_num'],3)*100;
                     if($orderlist[$val['shopid']]['goods_amount_total']!=0){
                     $val['amount_mod']=round($val['goods_amount_total']/$orderlist[$val['shopid']]['goods_amount_total'],3)*100;   
                     }
                      
                }
                $all_num_mod+=$val['order_num']; 
                $refund_num_money+=$val['goods_amount_total']; 
                //dump($val['order_num']);
                $val['all_order_num']=$orderlist[$val['shopid']]['order_num'];
                $val['amount_total']=$orderlist[$val['shopid']]['goods_amount_total'];
                $datalist[]=$val;
                $rfallsubtotal+=$val['all_order_num'];
                $rfallcosprice+=$val['amount_total']; 
            }
            $orderrefund['allsubtotal']=$rfallsubtotal;
            $orderrefund['allcosprice']=$rfallcosprice;
            $orderrefund['refund_num']=$all_num_mod;
            $orderrefund['refund_num_money']=$refund_num_money;//sss
            if($rfallsubtotal!=0){
                $orderrefund['refund_num_mod']=round($all_num_mod/$rfallsubtotal,3)*100;
                $orderrefund['refund_num_money_mod']=round($refund_num_money/$rfallcosprice,3)*100;    
            }
            
            if($orderbydata==1){
                $datalist=$this->sort_list($datalist,'num_mod');    
            }
            $tpl_data['order_refund']=$orderrefund;
            $tpl_data['order_refundlist']=$datalist;//直发退款数据
            //dump($datalist);
            
            //直发统计数据
             if($shopname)$wherestr=" AND shopname in('".$whereshop."')";
            $orders=$this->m->getOrderAmountList($starttime,$wherestr,$endtime,"dates",'dates');
            $daysales=array();
            foreach($orders as $key=>$val){
                $subtotal = $val['goods_amount_total'] +$val['shipping_fee_total'];
                $subzhic = $val['costprice_total']+$freight+$val['realexpress_fre']+ $val['payfee_total']+ $val['platform_fee_total'];
                $lirun = $subtotal - $subzhic;
        		if($subtotal){
        			$maoliv = round(($lirun/$subtotal)*100,2);
        		}else{
        			$maoliv=0;
        		}    
                $res=array("orderAmount"=>$val['goods_amount_total'],"shipping_fee"=>$val['shipping_fee_total'],"subtotal"=>number_format($subtotal,2),
                "cosprice"=>$val['costprice_total'],"freight"=>$val['realexpress_fre']
                ,"platformfee"=>$val['platform_fee_total'],"payfee"=>$val['payfee_total'],'orderDate'=>$val['dates'],
                "subzhic"=>number_format($subzhic,2),"goodsnNum"=>$val['sell_total'],"orderNum"=>$val['order_num'],"lirun"=>number_format($lirun,2),"maoliv"=>$maoliv."%");
                $daysales[]=$res;
                
          		$allorderAmount = $allorderAmount+$val['goods_amount_total'];	//合计
        		$allshipping_fee = $allshipping_fee+$val['shipping_fee_total'];
        		$allsubtotal = $allsubtotal+$subtotal;
        		$allcosprice = $allcosprice+$val['costprice_total'];
        		$allnum = $allnum+$val['sell_total'];
        		$allorderNum = $allorderNum+$val['order_num'];
        		$allfreight = $allfreight+$val['realexpress_fre'];
        		$allplatformfee = $allplatformfee+$val['platform_fee_total'];
        		$allpayfee = $allpayfee+$val['payfee_total'];
        		$allsubzhic = $allsubzhic+$subzhic;
        		$alllirun = $alllirun+$lirun;
            }
            $tpl_data['list']=$daysales;
            if($allsubtotal) $allmaolv = round(($alllirun / $allsubtotal)*100,2);
        	$saletotal["allorderAmount"]=number_format($allorderAmount,2);
        	$saletotal["allshipping_fee"]=number_format($allshipping_fee,2);
        	$saletotal["saleallsubtotal"]=number_format($allsubtotal,2);
        	$saletotal["allcosprice"]=number_format($allcosprice,2);
            $saletotal["imglist"]=array_reverse($daysales);
        	$saletotal["allnum"]=$allnum;
        	$saletotal["allorderNum"]=$allorderNum;
        	$saletotal["allfreight"]=number_format($allfreight,2);
        	$saletotal["allpayfee"]=number_format($allpayfee,2);
        	$saletotal["allsubzhic"]=number_format($allsubzhic,2);
        	$saletotal["alllirun"]=number_format($alllirun,2);
        	$saletotal["allmaolv"]=$allmaolv."%";
        	$saletotal["allplatformfee"]=number_format($allplatformfee,2);
            $tpl_data['saletotal']=$saletotal;//allsubzhic
            
            if($total_arr["i_total"]+$allorderAmount+$allshipping_fee>0){
                $avglirunlv=round(($alllirun+$total_arr["lirun"])/($total_arr["i_total"]+$allorderAmount+$allshipping_fee)*100,2);
            }
            $analyties=array('allorderAmount'=>$allorderAmount,'allshipping_fee'=>$allshipping_fee,'allsubtotal'=>$allsubtotal,
                'allcosprice'=>$allcosprice,'allsubzhic'=>$allsubzhic,'allfreight'=>$allfreight,
                'allplatformfee'=>$allplatformfee+$allpayfee,'allpayfee'=>$allpayfee,
                'allnum'=>$allnum,'allorderNum'=>$allorderNum,'alllirun'=>$alllirun,'alllirunlv'=>$allmaolv,'avglirunlv'=>$avglirunlv);
            $this->tpl->assign('anal',$analyties); 
        

            //FBA退款数据
            $re_endtime=$endtime." 23:59:59";
            $re_starttime=$starttime." 00:00:00";
            $date_where=$re_endtime!=''?"dates between '".$re_starttime."' and '".$re_endtime."'":"dates='".$re_starttime."'";
            $wherestr=' and A.amazon_id is not null';
            if($shopname)$wherestr .=" AND B.shopname in('".$whereshop."')";
            $all_orderinfo_where=$date_where;
            $refunddatalist=$this->fun->getdatabaseslist("db_amzordertmp B left join (select count(*) as
             goods_total,amazon_id from db_amzordertmp_refund $refund_date_where group by amazon_id) as A on A.amazon_id=B.id","$wherestr and {$date_where} group by B.shopid",
             'SUM(B.moneyrate * B.refundMoney) as refund_total,shopid as sku,shopname,amazon_id,count(*) as order_num,SUM(goods_total) as goods_num');
            $shopids=iarray_column($refunddatalist,'sku');
       
            $shopids_id_str=implode("','",$shopids);
            $orderwhere=" and shopid in('$shopids_id_str') ";
            $all_orderinfo=$this->fun->getdatabaseslist("db_amzordertmp","$orderwhere and  {$all_orderinfo_where} 
              group by sku","count(*) as order_num,shopid as sku,SUM(goods_amount+shipping_fee) as goods_amount_total");
             // echo $this->db->last_query();
            $orderlist=array();
            foreach($all_orderinfo as $key=>$val){
                $orderlist[$val['sku']]=$val;
            }
            $allsubtotal=$allcosprice=$all_num_mod=0;
            foreach($refunddatalist as $key=>$val){
                $val['goods_name']=$orderlist[$val['sku']]['productname'];
                $val['refund_total']=round($val['refund_total'],2);
                $val['all_order_num']=$orderlist[$val['sku']]['order_num'];  
                $val['amount_total']=round($orderlist[$val['sku']]['goods_amount_total'],2); 
                if($val['all_order_num']){
                     $val['num_mod']=round($val['order_num']/$orderlist[$val['sku']]['order_num'],4)*100;
                     $val['amount_mod']=round(abs($val['refund_total'])/$orderlist[$val['sku']]['goods_amount_total'],4)*100; 
                }
                $allsubtotal+=$val['all_order_num'];
                $allcosprice+=$val['amount_total']; 
                $all_num_mod+=$val['order_num']; 
                $refund_num_money+=$val['refund_total']; 
                $refunddatalist[$key]=$val;
            }
            
            $tpl_data['allsubtotal']=$allsubtotal;
            $tpl_data['allcosprice']=$allcosprice;
            $tpl_data['refund_num']=$all_num_mod;
            $tpl_data["shop_refundlist"]=$refunddatalist;
            $tpl_data['refund_num_money']=$refund_num_money;
      
            if($allsubtotal!=0){
                $tpl_data['refund_num_mod']=round($all_num_mod/$allsubtotal,3)*100;
                $tpl_data['refund_num_money_mod']=round(abs($refund_num_money)/$allcosprice,3)*100;
            }
            
            //fba库存报表
            $wherestr='';
            if($shopname)$wherestr=" AND shopname in('".$whereshop."')";
            $fba_store_list =  $this->fun->getdatabaseslist("db_fba_stock A left join db_goods as B on A.goods_id=B.goods_id",
            "$wherestr group by sku","*,max(A.id),count(*) as shop_sell_count,sum(Quantity) as Quantity_num,sum(costprice*Quantity) as costprice_num"," order by Quantity_num desc");
          
            $countsql ="SELECT COUNT(distinct(sku)) as total,sum(costprice*Quantity) as
                 total_costprice,sum(Quantity) as total_quantity FROM db_fba_stock where 1 $wherestr";    
            $totalinfo = $this->db->get_one($countsql);
            foreach($fba_store_list as $key=>$val){
                $val['createtime']=date('Y-m-d',$val['instime']);
                $order_list[$key]=$val;
            }
            $tpl_data['total_stock']=$totalinfo['total_quantity'];
            $tpl_data['total_costprice']=$totalinfo['total_costprice'];
            $tpl_data['stock_update_time']=$fba_store_list[0]['createtime'];
            $tpl_data['store_list']=$fba_store_list;
            
            //其它仓库存数
            $wherestr='';
            if($shopname)$wherestr=" AND shopname in('".$whereshop."')";
            $other_store_list =  $this->fun->getdatabaseslist("db_goods_stock A join (select distinct goods_id from db_fba_stock where 1 $wherestr) as B on A.goods_id=B.goods_id
            join db_goods C on C.goods_id=A.goods_id
            ",
            "&& storage_id<>9 group by A.goods_id",
            "C.goods_sku,C.goods_name,C.bulkprice,C.g_costprice,sum(stock) as Quantity_num
            ,sum(stock*bulkprice) as factory_price,sum(stock*g_costprice) as made_price"," order by Quantity_num desc");
            foreach($other_store_list as $key=>$val){
                $totalinfo['other_total_quantity']+=$val['Quantity_num'];
                $totalinfo['other_total_costprice']+=$val['made_price'];
            }
            $tpl_data['other_total_stock']=$totalinfo['other_total_quantity'];
            $tpl_data['other_total_costprice']=$totalinfo['other_total_costprice'];
            $tpl_data['other_store_list']=$other_store_list;
            //运输计划数据
            $where='';
    		if($re_starttime){
    			$where.=" AND createtime >='".$re_starttime."'";
    		}
    		if($re_endtime){
    			$where.=" AND createtime <='".$re_endtime."'";
    		}
            if($shopname)$where.=" AND shopname in('".$whereshop."')";
            $where.=" && status=5";
            $oversea_ship = $this->fun->getdatabaseslist('t_transportationplanning',$where);

            $list['list']=$oversea_ship;
    		//echo $this->db->last_query();
            $skus=$quantity_num=$costprices=0;
    		foreach($list["list"] as $key=>$rs){
    			$where = " AND id = '".$rs["oversearproduct_id"]."'";
    			$packingman = explode("|",$this->config->item('packingman'));
    			if(in_array($_COOKIE["username"],$packingman))
    			{
    				$list["list"][$key]["mods"] = 1;	//封箱人员权限
    			}else{
    				$list["list"][$key]["mods"] = 0;
    			}
    			if($_COOKIE["username"] == $rs["createoper"])
    			{
    				$list["list"][$key]["mod"] = 1;
    			}else{
    				$list["list"][$key]["mod"] = 0;
    			}
                $skus+=$rs['skunum'];
                $quantity_num+=$rs['totalnum'];
                $costprices+=$rs['totalamount'];
                
    		}
             $tpl_data['overseatal']=array('skus'=>$skus,'quantity_num'=>$quantity_num,'costprices'=>number_format($costprices,2));
            $tpl_data['overseadeliver']=$list['list'];
        }
        $this->tpl->assign($tpl_data); 
        $this->tpl->display("report/fbaShopSells.tpl");
    }
    
    //fba库存报表
    public function fbaStock(){
        $pageSize=50;
        $shopname=$this->input->get('shopname');   
        $selltype=$this->input->get("selltype");
        $getsort=$this->input->get('orderstr');
        $search_sku=trim($this->input->get("search_sku"));
        $nowpage = $_REQUEST["pageid"];
        $selltype=$selltype==''?'SELLABLE':$selltype;
	    if ($nowpage == "") $nowpage = 1;   
        $can_visit_shop=$this->getViewShops();
        if($can_visit_shop!='isadmin' && $shopname==''){
            //if(!empty($getstarttime)){
                $shopname=$can_visit_shop;
            //}
        }    
        $tpl_data=array('search_sku'=>$search_sku,'endtime'=>$endtime,'shopname'=>$shopname,'selltype'=>$selltype,'orderstr'=>$getsort);
        
        $whereshop=str_replace(',',"','",$shopname);
        if($shopname)$wherestr=" AND shopname in('".$whereshop."')";
        
        if($selltype=='UNKNOWGoods'){
                
        }else{
            $wherestr.=" and Warehouse_code='$selltype'";
            $shop_where.=" and Warehouse_code='$selltype'";    
        }
        

        
        if($search_sku){
            $wherestr.=" and ( sku like '%".$search_sku."%' or asin ='".$search_sku."')"; 
            $shop_where.=" and ( sku like '%".$search_sku."%' or asin ='".$search_sku."')";  
        }

        $pageSize=100;
        if ($nowpage !='') {
            $offset = ($nowpage - 1) * $pageSize;
            $limit = " LIMIT $pageSize OFFSET $offset";
        }
        if($orderDate!='' or $end_date!=''){
            $date_where=$end_date!=''?"and dates between '".$orderDate."' and '".$end_date."'":"and dates='".$orderDate."'";
        }
        $orderstr="Quantity_num desc";
        if($getsort){
            $orderstr=str_replace("__"," ",$getsort); 
            if(strpos($orderstr,'desc')>0){
                $tpl_data['orderbyst']='desc';
            };   
        }
        
        $this->tpl->assign("d_shop", $this->fun->getdatabaseslist('db_fba_stock', $shop_where." and shopid>0", 'distinct shopname as name,shopid as id', ' order by id asc')); 
        
        if($selltype=='UNKNOWGoods'){
            $wherestr.=" and B.goods_id is null ";  
            $countsql ="SELECT COUNT(distinct(sku)) as total FROM db_fba_stock left join db_goods as B on db_fba_stock.goods_id=B.goods_id
             where 1 $wherestr  {$date_where}";
        }else{
            $countsql ="SELECT COUNT(distinct(sku)) as total FROM db_fba_stock where 1 $wherestr  {$date_where}";    
        }
        
        $refundCount = $this->db->get_one($countsql);
        $tpl_data['datatotal']=$refundCount['total'];
        if($selltype=='UNKNOWGoods'){
            
            $countsql="SELECT COUNT(distinct(sku)) as total,sum(costprice*Quantity)
             as total_costprice,sum(Quantity) as total_quantity FROM db_fba_stock left join db_goods as B on db_fba_stock.goods_id=B.goods_id
              where 1 $wherestr  {$date_where}";         
        }else{
            $countsql ="SELECT COUNT(distinct(sku)) as total,sum(costprice*Quantity) as
             total_costprice,sum(Quantity) as total_quantity FROM db_fba_stock where 1 $wherestr  {$date_where}";    
        }
        //
        
        $totalinfo = $this->db->get_one($countsql);
        $pageList = $this->pagenav->page($tpl_data["datatotal"], $nowpage, $pageSize);
        $this->tpl->assign("totalpage", ceil($tpl_data["datatotal"] / $pageSize));
        $this->tpl->assign("total", $result["total"]);
        $this->tpl->assign("pageList", $pageList);
        
        
        $order_list =  $this->fun->getdatabaseslist("db_fba_stock A left join db_goods as B on A.goods_id=B.goods_id","$wherestr  {$date_where}
         group by sku","*,count(*) as shop_sell_count,sum(Quantity) as Quantity_num,sum(costprice*Quantity) as costprice_num",
         'order by '.$orderstr.$limit);
        //dump($order_list);
        $sku_list=iarray_column($order_list,'sku');
        $sku_list_str=implode("','",$sku_list);
         $sale_shops=$this->fun->getdatabaseslist('db_fba_stock', " and sku in('".$sku_list_str."')
         and shopid>0", 'shopname ,shopid,sku', ' group by shopname,sku order by id asc');
        $new_sale_shops=array();
        foreach($sale_shops as $key=>$val){
            $new_sale_shops[$val['sku']][]=$val['shopname'];
        }
        foreach($new_sale_shops as $key=>$val){
            $new_sale_shops[$key]=count($val);//implode(',',$val);
        }
        
        foreach($order_list as $key=>$val){
            $val['createtime']=date('Y-m-d',$val['instime']);
            $order_list[$key]=$val;
        }
        $tpl_data['sale_shops']=$new_sale_shops;
        $tpl_data['total_stock']=$totalinfo['total_quantity'];
        $tpl_data['total_costprice']=$totalinfo['total_costprice'];
        $tpl_data['stock_update_time']=$order_list[0]['createtime'];
        $tpl_data['list']=$order_list;
        
		$rshop = $this->db->get_where("d_shop","name='".$shop_id."'")->result_array();
        $this->tpl->assign("shopsid", $rshop[0]["id"]);
        $this->tpl->assign($tpl_data);
        $this->tpl->display("report/fbaStock.tpl");       
    }
    
    public function getShopSaleNum(){
        $sku=$this->input->get('sku');
        $selltype=$this->input->get('selltype');
        if($selltype!='UNKNOWGoods'){ 
            $wherestr.=" and Warehouse_code='$selltype'"; 
        }
        $sale_shops=$this->fun->getdatabaseslist('db_fba_stock', "$wherestr and sku in('".$sku."')
         and shopid>0", 'shopname,shopid,sku,sum(Quantity) as Quantity', 'group by shopname order by id asc');
         echo "<table align='center' border='0' class='stdtable' cellspacing=0 cellpadding='0'>";
         echo "<tr><td style='padding:3px 5px;'><strong>&nbsp;&nbsp;店铺</strong></td><td><strong> sku</strong></td><td><strong>&nbsp;&nbsp;库存</strong></td></tr>";
        foreach($sale_shops as $key=>$val){
            echo "<tr><td style='padding:3px 5px;'>&nbsp;&nbsp;{$val[shopname]}</td><td style='padding:3px 3px;'>&nbsp;&nbsp;{$val[sku]}</td>
            <td style='padding:3px 5px;'>&nbsp;&nbsp;{$val[Quantity]}</td></tr>";
        }
        echo "</table>";
    }
    
    
    public function reportStore(){
        $shopname=$this->input->get('shopname');   
        $selltype=$this->input->get("selltype");
        $getsort=$this->input->get('orderstr');
        $search_sku=$this->input->get("search_sku");
        $selltype=$selltype==''?'SELLABLE':$selltype;
        if($selltype=='UNKNOWGoods'){
            $wherestr.=" and B.goods_id is null ";          
        }else{
            $wherestr=" and Warehouse_code='$selltype'";    
        }
        if($shopname){
			$shopname = explode(",",$shopname);
			$shopname = array_filter($shopname);
			$shopname = implode("','",$shopname);
			
            $wherestr.=" and shopname in('".$shopname."')";   
        }
        if($search_sku){
            $wherestr.=" and sku like '%".$search_sku."%'";   
        }
        if($orderDate!='' or $end_date!=''){
            $date_where=$end_date!=''?"and dates between '".$orderDate."' and '".$end_date."'":"and dates='".$orderDate."'";
        }
        $orderstr="Quantity_num desc";
        if($getsort){
            $orderstr=str_replace("__"," ",$getsort);  
        }
        $countsql ="SELECT COUNT(distinct(sku)) as total,sum(costprice*Quantity) as
             total_costprice,sum(Quantity) as total_quantity FROM db_fba_stock A left join db_goods as B on A.goods_id=B.goods_id where 1 $wherestr  {$date_where}";    
        $totalinfo = $this->db->get_one($countsql);
        
        $order_list =  $this->fun->getdatabaseslist("db_fba_stock A left join db_goods as B on A.goods_id=B.goods_id","$wherestr  {$date_where}
         group by sku","*,count(*) as shop_sell_count,sum(Quantity) as Quantity_num,sum(costprice*Quantity) as costprice_num",
         'order by '.$orderstr);
	
        require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
        //.....此处略去从数据库获取数据的过程，$a为需要导出的数组......

        $numArr = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        // Create new PHPExcel object
        $objPHPExcel = new PHPExcel();
        //NO. 	商品编号 	名称 	总库存数 	总成本价值
        $arr = array('商品编号','名称','总库存数', '总成本价');
        // 输出标题
        //echo date('H:i:s') , " Add some data" , EOL;
        //设置换行
        //$objPHPExcel->getActiveSheet()->getStyle('H')->getAlignment()->setWrapText(true);
        $objPHPExcel->getActiveSheet()->getStyle('Y')->getAlignment()->setWrapText(true);
        //设置相应列的宽度
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(20);
        //weight_waring
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(50);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(15);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(15);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('H')->setWidth(25);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('I')->setWidth(15);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('J')->setWidth(15);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('K')->setWidth(25);
        //输出第一行
        $objPHPExcel->setActiveSheetIndex(0)
           ->setCellValue('A1', $arr[0])
         ->setCellValue('B1', $arr[1])
         ->setCellValue('C1', $arr[2])
         ->setCellValue('D1', $arr[3])
         ->setCellValue('E1', $arr[4])
         ->setCellValue('F1', $arr[5])
         ->setCellValue('G1', $arr[6])
         ->setCellValue('H1', $arr[7])
         ->setCellValue('I1', $arr[8])
         ->setCellValue('J1', $arr[9])
           ->setCellValue('K1', $arr[10])
           ->setCellValue('L1', $arr[11]);
         
         //dump($order_list[1]);
        //输出内容
        for($i=0;$i<count($order_list);$i++){
          $a=$order_list;


          $objPHPExcel->getActiveSheet()->getStyle($numArr[0].($i+2))->getFont()->getColor()->setARGB("00".$td_color);
         $objPHPExcel->setActiveSheetIndex(0)
          ->setCellValueExplicit($numArr[0].($i+2), $a[$i]['sku'])
          ->setCellValueExplicit($numArr[1].($i+2), $a[$i]['goods_name'])
          ->setCellValue($numArr[2].($i+2), $a[$i]['Quantity_num'])
          ->setCellValue($numArr[3].($i+2), $a[$i]['costprice_num'])
          ->setCellValue($numArr[4].($i+2), $a[$i]['weight'])
          ->setCellValue($numArr[5].($i+2), $a[$i]['deliverFee'])
          ->setCellValue($numArr[6].($i+2), $a[$i]['fee'])
          ->setCellValueExplicit($numArr[7].($i+2), $a[$i]['orderId'])
          ->setCellValue($numArr[8].($i+2), '')
          //->setCellValue($numArr[9].($i+2), $td_color)
          ->setCellValue($numArr[10].($i+2), '');
          
        }
        $max_line=count($order_list);
        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue($numArr[0].($max_line+2), "合计：")
        ->setCellValue($numArr[2].($max_line+2), $totalinfo['total_quantity'])
          ->setCellValue($numArr[3].($max_line+2), $totalinfo['total_costprice']);
        //$totalinfo
        $site_root=$_SERVER['DOCUMENT_ROOT'];
          
        // Rename worksheet
        //echo date('H:i:s') , " Rename worksheet" , EOL;
        $dirName ="dhlexpress";//目录名
        $old_filename=$filename;
        //$filename = iconv("utf-8","gb2312//IGNORE",$filename);
        $fileName = "FBA_store_".date("Y-m-d");//文件名\uploads\DHL
        $objPHPExcel->getActiveSheet()->setTitle('Sheet1');
         
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);
         
        // Save Excel 2007 file
        //echo date('H:i:s') , " Write to Excel2007 format" , EOL;
        $callStartTime = microtime(true);

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save($site_root.'/uploads/'.$dirName.'/'.$fileName.'.xlsx');
         
        header('Location:http://'.$_SERVER['HTTP_HOST'].'/uploads/'.$dirName.'/'.$fileName.'.xlsx');
    }
    
    public function sort_list($arr, $keys, $type = 'desc') {
        $keysvalue = $new_array = array();
        foreach ($arr as $k => $v){
            $keysvalue[$k] = $v[$keys];
        }
        $type == 'asc' ? asort($keysvalue) : arsort($keysvalue);
        reset($keysvalue);
        foreach ($keysvalue as $k => $v) {
            $arr[$k]['sortindex']=count($new_array)+1;
           $new_array[$k] = $arr[$k];
        }
        return $new_array;
    }
    
    public function getViewShops(){
        $authname=$_COOKIE['username'];
        $viewshopname = $_COOKIE["shopname"];	//开通了权限的人员需要绑定店铺
        if($viewshopname){
        	$viewshopname = unserialize($viewshopname);
            if(!is_array($viewshopname)){$viewshopname=array();}
            if(in_array('all',$viewshopname)){
                $lookshops='all';
            }
        }       
        if($_COOKIE["department"] ==1 || $_COOKIE["power"]=='all' || $_COOKIE["department"]=='5' || $lookshops=='all'){//管理者能看到所有店铺
			$where = "";
            return 'isadmin';
		}else{
		    $viewsshops=array();
            $viewshopname = $_COOKIE["shopname"];	//开通了权限的人员需要绑定店铺
			if($viewshopname){
				$viewshopname = unserialize($viewshopname);
				if($viewshopname){
					foreach($viewshopname as $key=>$name){
                        $viewsshops[]=$name;
					}
				}
			}
            
            
            $where=" and (updateoper='".$authname."' or otherUpload like '%$authname%')";
            $shopname  = $this->d->selectShop($where);
            
            if(count($shopname)>0){
                foreach($shopname as $key=>$platlist){
                    foreach($platlist as $index=>$val){
                        $val['otherUpload']=explode(',',$val['otherUpload']);
                        if($val['updateoper']!=$authname and !in_array($authname,$val['otherUpload'])){
                            unset($shopname[$key][$index]);
                        }else{
                            $viewsshops[]=$val['name'];
                        }
                    }
                }
                
            }
            $viewshop=implode(",",$viewsshops);
            return $viewshop;
		}
    }
    
    public function getShopList(){
        $authname=$_COOKIE['username'];
        $viewsshops=array();
        $viewshopname = $_COOKIE["shopname"];	//开通了权限的人员需要绑定店铺
        if($viewshopname){
        	$viewshopname = unserialize($viewshopname);
            if(!is_array($viewshopname)){$viewshopname=array();}
            if(in_array('all',$viewshopname)){
                $lookshops='all';
            }
        }       
        if($_COOKIE["department"] ==1 || $_COOKIE["power"]=='all' || $_COOKIE["department"]=='5' || $lookshops=='all'){//管理者能看到所有店铺
			$where = "";
		}else{
            $viewshopname = $_COOKIE["shopname"];	//开通了权限的人员需要绑定店铺
			if($viewshopname){
				$viewshopname = unserialize($viewshopname);
				if($viewshopname){
					foreach($viewshopname as $key=>$name){
                        $viewsshops[]=$name;
                        
					}
                    $view_shopstr=implode("','",$viewsshops);
				}
			}
            $where=" and (updateoper='".$authname."' or name in('".$view_shopstr."') or otherUpload like '%$authname%')";
		}
        //updateoper,otherUpload
        $fbatype=$this->input->post("fbatype");
        if($fbatype==1){
            //if(count($goods_id_list)>0)$goods_wherestr=" AND goods_id in(".$goods_id_str.")";
            $shop_list=$this->fun->getdatabaseslist("db_amzordertmp"," and shopid>0","distinct shopname,shopid");
            $shop_id_list=iarray_column($shop_list,"shopid");
            $shop_id_str=implode(',',$shop_id_list);
            if(count($shop_id_list)>0){
                $where.=" AND id in(".$shop_id_str.") and platfrom=2";
            }
        }
		$shopname  = $this->d->selectShop($where);
        if($_COOKIE["department"] ==1 || $_COOKIE["power"]=='all' || $_COOKIE["department"]=='5' || $lookshops=='all'){//管理者能看到所有店铺
			
		}else{ //过虑没有权限的店铺
            if(count($shopname)>0){
                foreach($shopname as $key=>$platlist){
                    foreach($platlist as $index=>$val){
                        $val['otherUpload']=explode(',',$val['otherUpload']);
                        if($val['updateoper']!=$authname and !in_array($authname,$val['otherUpload']) and !in_array($val['name'],$viewsshops)){
                            unset($shopname[$key][$index]);
                        }
                    }

                }
            }
            
        }
        if(!is_array($shopname['ebay'])){
            $shopname['ebay']=array();
        }
        if(empty($shopname['Amazon']))$shopname['Amazon']=array();
        if(empty($shopname['ebay']))$shopname['ebay']=array();
        $Amazon_shops=array_merge($shopname['Amazon'],$shopname['ebay']);
        $Amazon_shops=$this->sort_list($Amazon_shops,'country','asc');
        
        foreach($Amazon_shops as $key=>$val){
            $val['country']=$val['country']==0?1:$val['country'];
            $country_shops[$val['country']][]=$val;
        }
        $shopgroup =$this->fun->get_sys_goods_status('sys_shop_group');
        $this->tpl->assign('shopgroup',$shopgroup);
        // array('未分类','美国','日本','德国','外部','欧洲','美国一组','美国二组')
         
             
        $selected_array=$this->input->post("selected");
        $selected_array=explode(',',$selected_array);
        $this->tpl->assign('country_shops',$country_shops);
        $this->tpl->assign("selected_array",$selected_array);
		$this->tpl->assign("shopname",$shopname);
        $data=$this->tpl->fetch('report/getShopList.tpl');
        echo $data;  
    }
    
	
	function order(){
		if($_COOKIE["department"] ==1 || $_COOKIE["power"]=='all' || $_COOKIE["department"]=='5')	//管理者能看到所有店铺
		{
			$where = "";
		}else{
			$shopname = $_COOKIE["shopname"];	//开通了权限的人员需要绑定店铺
			if($shopname)
			{
				$shopname = unserialize($shopname);
                if(!in_array('all',$shopname)){
    				$where = " AND (";
    				foreach($shopname as $key=>$name)
    				{
    					if($key>0)
    					{
    						$or = " or";
    					}
    					$where.=" $or name = '".$name."'";
    				}
    				$where.=") ";
                }
			}else{
				die('如果你要查看店铺报表，请先绑定店铺！');//没有绑定的人员不开放权限
			}
		}
		$times = time()-86400*30;
		$this->tpl->assign("starttime",date('Y-m-d',$times));
		$this->tpl->assign("endtime",date('Y-m-d'));
		$shopname  = $this->d->selectShop($where);
		$this->tpl->assign("shopname",$shopname);
		$this->tpl->display("report/order.tpl");
	}

	function reportorder(){
		if($_COOKIE["department"] ==1 || $_COOKIE["power"]=='all' || $_COOKIE["department"]=='5'){//管理者能看到所有店铺
			$where = "";
		}else{
			$shopname = $_COOKIE["shopname"];	//开通了权限的人员需要绑定店铺
			if($shopname){
				$shopname = unserialize($shopname);
				$where = " AND (";
				foreach($shopname as $key=>$name){
					if($key>0){
						$or = " or";
					}
					$where.=" $or name = '".$name."'";
				}
				$where.=") ";
			}else{
				die('如果你要查看店铺报表，请先绑定店铺！');//没有绑定的人员不开放权限
			}
		}
		$times = time()-86400*30;
		$this->tpl->assign("starttime",date('Y-m-d',$times));
		$this->tpl->assign("endtime",date('Y-m-d'));
		$shopname  = $this->d->selectShop($where);
		$this->tpl->assign("shopname",$shopname);
		$this->tpl->display("report/reportorder.tpl");
	}
	
	function Oustock(){
		//待发货订单中，缺货报表
		 $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "")
            $nowpage = 1;
        $where = " AND (B.order_status=2 or B.order_status=3)  AND C.storage_id=1 AND A.goods_sn !='ExtraFee' AND A.goods_sn !='rush2'";


		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$where.="  AND D.g_supplier= 1";
		}

		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$where.=" AND D.g_supplier = 2";
		}

		if ($this->input->get_post('supplier')) {
			$where .= " AND D.g_supplier='" . trim($this->input->get_post('supplier')) . "'";
			$this->tpl->assign("supplier", trim($this->input->get_post('supplier')));
		}




		$other = trim($this->input->get('other'));
		if($other)
		{
			$where.=" AND A.goods_sn = '".$other."'";
			$this->tpl->assign("other",$other);
		}
		$buyer = trim($this->input->get('buyer'));
		if($buyer)
		{
			$where.=" AND D.g_buyer = '".$buyer."'";
			$this->tpl->assign("buyer",$buyer);
		}
		if($buyer=="")
		{
			if($_COOKIE["department"] != 1){
				$where.=" AND D.g_buyer = '".$_COOKIE["username"]."'";
			}
		}
		$where.=" and  length(A.goods_sn)!=8 AND (locate(11,A.goods_sn)!=1 or locate(12,A.goods_sn)!=1 ) ";
	
        $orderby = " GROUP BY A.goods_sn";

        $list = $this->fun->getalllist('`db_order_sell` A LEFT JOIN db_order_list B on A.order_id = B.order_id LEFT JOIN db_goods_stock C on A.goods_id = C.goods_id LEFT JOIN db_goods D on A.goods_id = D.goods_id', $where, $nowpage, $if_csv, 200, $orderby,"A.goods_id,goods_sn,SUM(A.goods_number) as goods_number,C.*");
		//echo $this->db->last_query();
        foreach ($list["list"] as $key => $rs) {
			//$rsdb = $this->fun->getdatabasesdetail("`db_order_sell` A LEFT JOIN db_order_list B on A.order_id = B.order_id LEFT JOIN db_goods_stock C on A.goods_id = C.goods_id"," AND (B.order_status=2 or B.order_status=3) and B.is_que=1 AND goods_id={$rs[goods_id]} AND C.storage_id=1","SUM(goods_number) as number");
			if($rs["goods_number"]>$rs["stock"]){
				$rsdb = $this->fun->getdatabasesdetail('db_goods'," AND goods_id = '".$rs['goods_id']."'");
				$rs["goods_name"] = $rsdb["goods_name"];
				$rsimages = $this->fun->getdatabasesdetail('db_goods_images'," AND goods_id = '".$rs['goods_id']."'");
			
				
				 if ($rsimages["thumb_url"]) {
                   	$rs["thumb_url"] = $rsimages["thumb_url"];
                }elseif ($rsimages['local_url']) {
						$rs["thumb_url"] =  "/".$rsimages["local_url"];
                }elseif ($rsimages['images_url']) {
					$rs["thumb_url"] =  "/".$rsimages["imagesurl"];
                } else {
					//如果没有获取到图片，再次读取父商品的图片
					  $rs["thumb_url"]  = "/fuman/images/s-l500.jpg";
                }

				$newlist[]= $rs;
			}
			
        }
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("goodslist", $newlist);
		$userlist = $this->fun->getdatabaseslist('db_goods'," AND g_buyer is NOT NULL",'DISTINCT(g_buyer)');
		foreach($userlist as $key=>$rs)
		{
			$yuanl[] = $rs['g_buyer'];
		}
        $this->tpl->assign("userlist", $yuanl);
		$this->tpl->assign("factory", $this->db->get('db_factory')->result_array());
        $this->tpl->display("report/Oustock.tpl");

	}
	public function showGoodstockByDay(){
		$nowpage = $_REQUEST["pageid"];
		if ($nowpage == "")
			$nowpage = 1;
		$where = "";
		$starttime = trim($this->input->get_post("starttime"));
		if($starttime){
			$where.= " AND addTime >= '{$starttime}' ";
			$this->tpl->assign("starttime",$starttime);
		}
		$endtime = trim($this->input->get_post("endtime"));
		if($endtime){
			$time = $endtime." 23:59:59 ";
			$where.= " AND addTime <= '{$time}' ";
			$this->tpl->assign("endtime",$endtime);
		}
		$list = $this->fun->getalllist('db_goodstock_statistics',$where,$nowpage,$if_csv,$this->pageSize);
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
		$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
		$this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this -> tpl -> display("report/goodstocklist.tpl");

	}
    

}
